※ 本文轉寄自 ptt.cc, 文章原始頁面
看板C_and_CPP
標題

[問題] C 語言考題請教

留言22則留言,10人參與討論
推噓9 ( 9013 )
各位好 我看不出來以下兩個 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://www.ptt.cc/bbs/C_and_CPP/M.1705336433.A.C84.html

22 則留言

NciscalA, 1F
一個 a b 有被修改,另一個沒有

mmmmei, 2F
應該是極值的問題吧?cmp1假如a或b是INT_MIN那取負數看平

mmmmei, 3F
台可能會變INT_MAX。但cmp2的abs(INT_MIN)會UB

ichunlai, 4F
cmp2的ABS是macro,有丟到編譯器看看嗎?我也很好奇結果

ichunlai, 5F
是啥

ichunlai, 6F
啊,我猜cmp2在任何負值(譬如-1)可能會變成--1之類的狀

ichunlai, 7F

ichunlai, 8F
跑了一下,我上面的回答沒想清楚,題目1的答案是(int_mi

ichunlai, 9F
n+1)到-1之間print的值不同,原因同一樓所述,題目二是

ichunlai, 10F
全相同

thomas2005, 11F
謝謝各位

kakar0to, 12F
這題好像只考到大家來找碴的感覺 沒考到什麼重點

xam, 13F
就考這樣啊 一堆bug寫這樣看你找不找的出來

wulouise, 14F
cmp2有UB嗎?兩邊除了印的不一樣有差嗎?

LPH66, 15F
有號數對 INT_MIN 取負可能溢位, 而有號數溢位是 UB

LPH66, 16F
然後其實這一點對 cmp1 和 cmp2 都是一樣的

LPH66, 17F
(因為不論是否經過巨集, 兩邊都有直接取負的運算)

LPH66, 18F
嘛, 講「可能」溢位是早期 C/C++ 的定義了, C++20 的有號數

LPH66, 19F
固定為二補數所以 INT_MIN 取負真的是溢位

chuegou, 20F
看最大負值取abs溢位看半天 看推文才發現ab有被改

Schottky, 21F
想得太深入反而會被劃╳的題目類型

kakar0to, 22F
樓樓上 這題就是大家來找碴的感覺 以為是考macro@@