题目
1.阅读以下程序,写出其输出结果。#include int fun(int n) {static int cnt = 0;cnt++;if (n <= 1) return 1;return fun(n-1) + fun(n-2) + cnt;}int main() {printf("%d", fun(3));return 0;}
1.阅读以下程序,写出其输出结果。
#include
int fun(int n) {
static int cnt = 0;
cnt++;
if (n <= 1) return 1;
return fun(n-1) + fun(n-2) + cnt;
}
int main() {
printf("%d", fun(3));
return 0;
}
题目解答
答案
分析`fun(3)`的递归过程:
1. `fun(3)`中,`cnt = 1`,需计算`fun(2) + fun(1) + 5`。
2. `fun(2)`中,`cnt = 2`,返回`fun(1) + fun(0) + 4 = 1 + 1 + 4 = 6`。
3. `fun(1)`(第二次)中,`cnt = 5`,返回1。
4. 最终结果为`6 + 1 + 5 = 12`。
程序输出结果为:
```
12
```