[问题] 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