从这个源程序很容易就看出有一个同自己名字的函数在里面,所以以后我们看到一个函数里面调用自己就是递归函数了。而且我们看一个递归函数就主要就是看它是否一个返回的条件,就好像一条又黑又深的山洞,我们前去探险如果往到底就一定要回头,就算是更深的也要返回啊!所以我们判定一个递归函数是否成立也常常是看它的返回条件。至于上面的那个源程序我也不想多说了,应该大家也看得明白。
这里就看看另一个利用递归函数做的题目吧,就是诺汉塔(老潭的书上也是有的)。
#include
void move(char x,char y)
{
printf("%c-->%c\n",x,y);
}
void hanoi (int n,char one ,char two,char three)
{
if(n==1) move (one ,three);
else
{
hanoi (n-1,one,three,two);
move(one,three);
hanoi(n-1,two,one,three);
}
}
main()
{
int m;
printf("input the number of diskes:");
scanf("%d",&m);
printf("the step to moving %3d diskes:\n",m);
hanoi(m,'A','B','C');
}
/*运行情况如下:
input the number of diskes:3 回车
the step to moving 3 diskes:
A-->C
A-->B
C-->B
A-->C
B-->A
B-->C
A-->C
书上说hanoi(n-1,one,three,two);是把"one"上的n-1个往"two"上移,接着move(one,three);然后是hanoi(n-1,two,one,three)即把"two"上的n-1个往"three"上移;
|h(2,1,3,2)|h(1,1,2,3)=>move(1,3) move(3,2) move(2,1) move(1,3) j)
{
int k=1,i=2,j=3;
pirntf("%d\n",i*3);
printf("%d\n",j*10);
}
printf("%d",k);
}