繁体   English   中英

更新移动计数(计数器)-河内的塔楼-C程序

[英]Update Move Count (Counter) - Towers of Hanoi - C program

我编写了这个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;
}

最简单的事情是使count成为全局变量,即

#include <stdio.h>
void TOH(int,char,char,char);
unsigned int count;
/* what you have, but remove the declaration of `count` from `TOH` */

然后,您可以从TOHmain访问count ,它将是相同的变量。

您可能还希望仅在TOH增加一次count (我想TOHprintf之后)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM