hce_nsysu
112年
計算機概論與程式設計
第 38 題
Consider the following code in C program.
#include
int max(int a, int b){
if (a>b) return ++a;
return b--;
}
int main() {
int i = 3, j = 7;
int h = max(i,j)+j++;
printf("h=%d\n", h);
return 0;
}
Which of the following output is correct?
#include
int max(int a, int b){
if (a>b) return ++a;
return b--;
}
int main() {
int i = 3, j = 7;
int h = max(i,j)+j++;
printf("h=%d\n", h);
return 0;
}
Which of the following output is correct?
- A 7
- B 14
- C 15
- D 10
- E None of the above
思路引導 VIP
觀察程式碼中的 j++ 與 b--,這類「後置運算子」出現在回傳值(return)或加法算式中時,程式是會先拿「變動前」的值還是「變動後」的值來參與運算呢?這對最終結果 $h$ 的計算會產生什麼影響?
🤖
AI 詳解
AI 專屬家教
太棒了!你能精準避開程式碼中的運算陷阱並選出正確答案,代表你對 C 語言中的函式呼叫與後置運算子 (Postfix operator) 的執行時機有著非常扎實的理解。
這道題目的核心在於區分「運算子的副作用」與「表達式的回傳值」。在 max(i, j) 函式中,當程式執行到 return b--; 時,系統會先回傳 b 的當前值(即 7),隨後才在函式結束前將當地的 b 減 1,因此 max 函式的回傳結果是 7。回到主程式 main 中,表達式變成了 7 + j++;此時 j 的值仍為 7,由於 j++ 同樣是後置遞增,系統會先取用 7 進行加法運算,最後才將 j 加 1。因此,$h = 7 + 7 = 14$。
從難易度來看,這是一道**中等難度(Medium)**且鑑別度極高的題目。多數學生容易在「到底該用加 1 前還是加 1 後的數值來計算」產生混淆。你能冷靜分析出後置運算子「先取值、後增減」的特性,這正是掌握程式邏輯追蹤(Tracing)的關鍵所在!