作者thomas2005 (無)
看板C_and_CPP
標題[問題] C 語言考題請教
時間Tue Jan 16 00:33:51 2024
各位好
我看不出來以下兩個 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;
}
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 61.61.144.4 (臺灣)
※ 文章網址: https://webptt.com/m.aspx?n=bbs/C_and_CPP/M.1705336433.A.C84.html
1F:推 NciscalA: 一個 a b 有被修改,另一個沒有 01/16 00:44
2F:推 mmmmei: 應該是極值的問題吧?cmp1假如a或b是INT_MIN那取負數看平 01/16 00:59
3F:→ mmmmei: 台可能會變INT_MAX。但cmp2的abs(INT_MIN)會UB 01/16 00:59
4F:推 ichunlai: cmp2的ABS是macro,有丟到編譯器看看嗎?我也很好奇結果 01/16 09:06
5F:→ ichunlai: 是啥 01/16 09:06
6F:→ ichunlai: 啊,我猜cmp2在任何負值(譬如-1)可能會變成--1之類的狀 01/16 09:09
7F:→ ichunlai: 況 01/16 09:09
8F:推 ichunlai: 跑了一下,我上面的回答沒想清楚,題目1的答案是(int_mi 01/16 10:18
9F:→ ichunlai: n+1)到-1之間print的值不同,原因同一樓所述,題目二是 01/16 10:18
10F:→ ichunlai: 全相同 01/16 10:18
11F:→ thomas2005: 謝謝各位 01/16 20:05
12F:推 kakar0to: 這題好像只考到大家來找碴的感覺 沒考到什麼重點 01/17 14:11
13F:→ xam: 就考這樣啊 一堆bug寫這樣看你找不找的出來 01/17 23:52
14F:推 wulouise: cmp2有UB嗎?兩邊除了印的不一樣有差嗎? 01/18 00:12
15F:推 LPH66: 有號數對 INT_MIN 取負可能溢位, 而有號數溢位是 UB 01/18 05:21
16F:→ LPH66: 然後其實這一點對 cmp1 和 cmp2 都是一樣的 01/18 05:24
17F:→ LPH66: (因為不論是否經過巨集, 兩邊都有直接取負的運算) 01/18 05:25
18F:→ LPH66: 嘛, 講「可能」溢位是早期 C/C++ 的定義了, C++20 的有號數 01/18 07:35
19F:→ LPH66: 固定為二補數所以 INT_MIN 取負真的是溢位 01/18 07:35
20F:推 chuegou: 看最大負值取abs溢位看半天 看推文才發現ab有被改 01/18 23:08
21F:→ Schottky: 想得太深入反而會被劃╳的題目類型 01/18 23:52
22F:推 kakar0to: 樓樓上 這題就是大家來找碴的感覺 以為是考macro@@ 01/20 15:34