我编写了这个 C 程序,用于在跟踪路径时将多个磁盘 (n) 从桩 A 移动到桩 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;
}
最佳答案
将 count
的值从您的函数返回到 main
。为此,您必须从 main
调用它作为
int c = TOH(n,'A','C','B');
并将函数的返回类型更改为 int
。
int TOH(int,char,char,char);
我稍微改变了你的功能:
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;
}
关于c - 更新移动计数(计数器)- 汉诺塔 - C 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20124650/