|
|
一个较奇特的递归程序解析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);
getch();
}
这是群中某朋友发的程序,要我帮着剖析原理,说实话,自己也是第一次见到这种形式的递归,我把它命名为“双重递归”吧。因为本人天资愚钝的缘故,所以花了较长时间去分析并尽最大努力将它表述出来。
我们先来看看该函数的递归次数
fun(6,&x);
在传入形参中,其中出现了“双重递归”
即:fun(n-1,&f1);
fun(n-2,&f2);
先n=6从主调函数传入,即
fun(5,&f1)+fun(4,&f2)等于最终递归完毕的结果(其实更准确的说法应该是递归最外层的f1+f2的值)
分析f1(中的值的递归变化)
fun(5,&f1)=fun(4,&f1)+fun(3,&f2)
fun(4,&f1)=fun(3,&f1)+fun(2,&f2)
fun(3,&f1)=fun(2,&f1)+fun(1,&f2)
fun(2,&f1)=1
分析f2(中的值的递归变化)
fun(4,&f2)=fun(3,&f1)+fun(2,&f2)
fun(2,&f2)=1
现在我们来回推
回推f1(中的值的递归变化)
fun(2,&f1)=1
fun(3,&f1)=fun(2,&f1)+fun(1,&f2)
fun(3,&f1)=1+1
fun(4,&f1)=fun(3,&f1)+fun(2,&f2)
fun(4,&f1)=2+1
fun(5,&f1)=fun(4,&f1)+fun(3,&f2)
fun(5,&f1)=3+(1+1)
回推f2(中的值的递归变化)
fun(2,&f2)=1
fun(4,&f2)=fun(3,&f1)+fun(2,&f2)
fun(4,&f2)=(1+1)+1
所以,fun(5,&f1)+fun(4,&f2)的最终结果是(3+(1+1))+((1+1)+1)=8
<递归结束 返回主调函数>
*s指向的是实参的x,所以printf("%d\n",x); 输出结果为8
|
|