- 34
- 0
- 约2.85千字
- 约 9页
- 2019-07-16 发布于四川
- 举报
3.下面程序的输出结果是( )。 #include stdio.h int f(int a, int b); int main(void) { int i = 2, p; p = f( i, i + 1 ); printf( “%d”, p); return 0; } int f( int a, int b) { int c; if (a b) { c = 1;} else if (a == b) { c = 0;} else {c = -1;} return c; } A) -1 B) 0 C) 1 D) 2 函数的递归调用 在调用一个函数的过程中,出现直接或间接地调用该函数本身,称为函数的递归调用。 f函数 调用f函数 f1函数 调用f2函数 f2函数 调用f1函数 int f (int x) { int z; if(x==0) return 1; if(x0) z=f (x-1); else if(x0) z=f (x+1); return (2*z); } #include stdio.h void recur(int); int main (void) { recur(1); return 0; } void recur(int n) //递归函数 { printf(第%d级调用\n, n); //1 if (n 4) { recur(n+1); //递归 } printf(第%d级返回\n, n); //2 } 输出结果: 第1级调用 第2级调用 第3级调用 第4级调用 第4级返回 第3级返回 第2级返回 第1级返回 解析: 从结果可以看出,1和2相当于循环体,当符合测试条件(即n4)时,#1部分循环;当测试条件为false时,2部分循环。 在递归函数中,位于递归调用之前的语句(即1部分),按被调函数(即recur())的顺序执行;位于递归调用之后的语句(即2部分),按被调函数相反的顺序执行。 每级函数调用都有自己的变量,递归调用就相当于又从头开始执行函数的代码。 每次函数调用都会返回一次,并且按顺序逐级返回递归。 #includestdio.h int fun(int n) //定义函数 { if(n==0||n==1) { n=1; } else { n=n*fun(n-1); //递归调用函数 } return n; } int main() { int i,j; printf(请输入一个数字:\n); scanf(%d,i); j=fun(i); printf(它的阶乘为: %d,j); } 有3个人坐在一起,问第3个人多少岁?他说比第2个人大2岁。问第2个人多少岁?他说比第1个人大2岁。最后问第1个人,他说是10岁。请问第3个人多大? 分析: age(3)=age(2)+2; age(2)=age(1)+2; age(1)=10; 归纳: n=1 age(n)=10 n1 age(n)=age(n-1)+2 程序如下: #include stdio.h int age(int n) { int c; if (n == 1) { c = 10; } else if (n 1) { c = age(n - 1) + 2; } return c; } int main(void){ printf(“%d”, age(3)); return 0; } 程序执行过程如下: int main(void){ printf(“%d”, age(3)); } int age(3) { int c; c = age(2) + 2; return c; } int age(2) { int c; c = ag
原创力文档

文档评论(0)