[問題] C 語言考題請教

作者: thomas2005 (無)   2024-01-16 00:33:51
各位好
我看不出來以下兩個 function 有什麼不同,請各位指教。
1.Do cmp1 and cmp2 print the same message for all possible inputs?
if not , please provide a case where they print it.
1.Do cmp1 and cmp2 return the same value for all possible inputs?
if not , please provide a case where they return it.
#define ABS(n) ((n<0)? -n:n)
int cmp1(int a , int b)
{
int result;
a=(a<0) ? -a: a;
b=(b<0) ? -b: b;
result=(a==b);
if(result)
printf("The absolute values of %d and %d are the same.",a,b);
else
printf("The absolute values of %d and %d are different.",a,b);
return result;
}
int cmp2(int a , int b)
{
int result=(ABS(a)==ABS(b));
if(result)
printf("The absolute values of %d and %d are the same.",a,b);
else
printf("The absolute values of %d and %d are different.",a,b);
return result;
}
作者: NciscalA   2024-01-16 00:44:00
一個 a b 有被修改,另一個沒有
作者: mmmmei (mmm煤)   2024-01-16 00:59:00
應該是極值的問題吧?cmp1假如a或b是INT_MIN那取負數看平台可能會變INT_MAX。但cmp2的abs(INT_MIN)會UB
作者: ichunlai (^_^)   2024-01-16 09:06:00
cmp2的ABS是macro,有丟到編譯器看看嗎?我也很好奇結果是啥啊,我猜cmp2在任何負值(譬如-1)可能會變成--1之類的狀況跑了一下,我上面的回答沒想清楚,題目1的答案是(int_min+1)到-1之間print的值不同,原因同一樓所述,題目二是全相同
作者: thomas2005 (無)   2024-01-16 20:05:00
謝謝各位
作者: kakar0to (Poker Face)   2024-01-17 14:11:00
這題好像只考到大家來找碴的感覺 沒考到什麼重點
作者: xam (聽說)   2024-01-17 23:52:00
就考這樣啊 一堆bug寫這樣看你找不找的出來
作者: wulouise (在線上!=在電腦前)   2024-01-18 00:12:00
cmp2有UB嗎?兩邊除了印的不一樣有差嗎?
作者: LPH66 (-6.2598534e+18f)   2024-01-18 05:21:00
有號數對 INT_MIN 取負可能溢位, 而有號數溢位是 UB然後其實這一點對 cmp1 和 cmp2 都是一樣的(因為不論是否經過巨集, 兩邊都有直接取負的運算)嘛, 講「可能」溢位是早期 C/C++ 的定義了, C++20 的有號數固定為二補數所以 INT_MIN 取負真的是溢位
作者: chuegou (chuegou)   2024-01-18 23:08:00
看最大負值取abs溢位看半天 看推文才發現ab有被改
作者: Schottky (順風相送)   2024-01-18 23:52:00
想得太深入反而會被劃╳的題目類型
作者: kakar0to (Poker Face)   2024-01-20 15:34:00
樓樓上 這題就是大家來找碴的感覺 以為是考macro@@

Links booklink

Contact Us: admin [ a t ] ucptt.com