#include<stdio.h>
int hanno(int n,char one, char two, char three)/*括号中形参的意思是,借助two将n个
石盘从one上移动到three上,所以写程序的
时候不要太死板了,好吗。本题值得再三
的看和体会*/
{
static int num = 0;
void movet(char x, char y);//当函数在下方定义时,记得在使用它的函数中声明一下
if (n == 1)
{
movet(one, three);
num++;
}
else
{
hanno(n - 1, one, three, two);
movet(one, three);
num++;
hanno(n - 1, two, one, three);
}
return num;
}
void movet(char x, char y)//one上只有一个时,这是最终操作
{
printf("%c->%c\n", x, y);
}
void main()
{
char one = 'A', two = 'B', three = 'C';
int n;
int num;
printf("请输入石盘个数:");
scanf_s("%d", &n);
num=hanno(n,one,two,three);
printf("一共移动%d次\n", num);
getchar();
getchar();
}
运行结果