少妇安吉娜 720p:C语言题,有关函数递归调用

来源:百度文库 编辑:查人人中国名人网 时间:2024/05/01 02:39:19
fun(int n,int *s)
{ int f1,f2;
if(n==1||n==2)*s=1;
else
{fun(n-1'&f2);
fun(n-2,&f2);
*s=f1+f2;
}
}
main()
{int x;
fun(6,&x);
printf("%d\n",x);
}
它的调用步骤是怎样的?*s=f1+f2最后是几加几?
fun(int n,int *s)
{ int f1,f2;
if(n==1||n==2)*s=1;
else
{fun(n-1,&f1);
fun(n-2,&f2);
*s=f1+f2;
}
}
main()
{int x;
fun(6,&x);
printf("%d\n",x);
}
它的调用步骤是怎样的?*s=f1+f2最后是几加几?

fun(6,&x)->if假->fun(5,&f1),fun(4,&f2) //5,3 8
fun(5,&x')->if假->fun(4,&f1),fun(3,&f2) //3,2 5
fun(4,&x'')->if假->fun(3,&f1),fun(2,&f2) //2,1 3
fun(3,&x''')->if假->fun(2,&f1),fun(1,&f2)//1,1 2
fun(3,&x'')->if假->fun(2,&f1),fun(1,&f2) //1,1 2

fun(4,&x')->if假->fun(3,&f1),fun(2,&f2) //2,1 3
fun(3,&x'')->if假->fun(2,&f1),fun(1,&f2) //1,1 2

5+3

fun(1,s),fun(2,s)...fun(n,s)的结果如下
1,1,2,3,5,8,....(fabnacci数列)
即每一个为他前两个的数字的和.
函数里面有一个很明显的递推关系
fun(n,s)=fun(n-1,s)+fun(n-2,s)