我编写了这个C程序,用于在跟踪路径时将多个磁盘(n)从peg A移动到peg C. 但是,我不知道如何/在何处进行计数调用/增量,以便在结尾处跟踪并打印出总移动次数.任何意见,将不胜感激.(最初我在TOH函数中打印它,这不起作用所以我删除了printf(..)行)我改变了变量,这样可以提高可读性; 但是,计数输出很远.对于板数= 3,计数= 239.对于板4的数量,计数= 130,431
#include <stdio.h>
int TOH(int,char,char,char);
int main()
{
int n;
printf("\nEnter number of plates:");
scanf("%d",&n);
int c = TOH(n,'A','C','B');
printf("\n");
printf("Total number of moves = %d \n ", c);
return 0;
}
int TOH(int n,char first,char third,char second)
{
int count;
if(n>0){
count=TOH(n-1, first, second, third);
printf("Move disk %d from peg %c to peg %c\n", n, first, third);
count++;
count+= TOH(n-1, second, third, first);
}
return count;
}
Run Code Online (Sandbox Code Playgroud)
count将函数的值返回到main.为此你必须从mainas 调用它
int c = TOH(n,'A','C','B');
Run Code Online (Sandbox Code Playgroud)
并将您的函数的返回类型更改为int.
int TOH(int,char,char,char);
Run Code Online (Sandbox Code Playgroud)
我改变了你的功能:
int TOH(int n,char x,char y,char z)
{
int count = 0;
if(n>0){
count = TOH(n-1, x, z, y);
printf("\nMove disk %d from peg %c to peg %c\n", n, x, y);
count++;
count += TOH(n-1, z, y, x) ;
}
return count;
}
Run Code Online (Sandbox Code Playgroud)