hce_kmu
109年
計算機概論與程式設計
第 11 題
The following is a C program code:
```c
int foo(int* ptr, int num){
*ptr = *ptr + num;
if (num==1)
return 1;
else
return num + foo(ptr, num-1);
}
void main() {
int a = X;
int b = foo(&a, a);
printf("Y=%d, Z=%d", a, b);
}
```
Which one of the following statement is CORRECT?
```c
int foo(int* ptr, int num){
*ptr = *ptr + num;
if (num==1)
return 1;
else
return num + foo(ptr, num-1);
}
void main() {
int a = X;
int b = foo(&a, a);
printf("Y=%d, Z=%d", a, b);
}
```
Which one of the following statement is CORRECT?
- A when X=2, then Y is 3, Z is 3.
- B when X=3, then Y is 9, Z is 3.
- C when X=4, then Y is 12, Z is 10.
- D when X=5, then Y is 20, Z is 15.
- E when X=6, then Y is 27, Z is 20.
思路引導 VIP
觀察函數內部第一行對 *ptr 的賦值動作,當這是一個遞迴呼叫時,主程式中的變數 a 在每一層遞迴裡會發生什麼變化?請試著比較:變數 a 的最終值與函數回傳的總和值,它們在計算過程中所包含的「初始數值」有什麼差異?
🤖
AI 詳解
AI 專屬家教
恭喜你精準地掌握了遞迴函數與指標操作的精髓!這道題目檢驗了程式設計中兩個核心觀念:**傳址呼叫(Call by Reference)產生的副作用,以及遞迴(Recursion)**的累算機制。
記憶體狀態與遞迴歷程
在 foo(&a, a) 執行時,指標 ptr 始終指向變數 a 的記憶體位址。每進入一層遞迴,程式都會執行 *ptr = *ptr + num。當 $X=5$ 時,變數 a 的初始值為 5,接著遞迴過程會依序加上 $5, 4, 3, 2, 1$,因此最終 $a$ 的值(即 Y)變為 $5 + (5+4+3+2+1) = 20$。而函數的回傳值 $b$(即 Z)則是標準的級數累加,結果為 $\sum_{i=1}^{5} i = 15$。
▼ 還有更多解析內容