汉诺塔c语言程序代码输出移动次数(c语言汉诺塔游戏)

C语言 汉诺塔输出某一次移动方案(第n次由x移到y柱)

#includestdio.h

void hanoi(int n,char a,char b,char c);

void move(int n,char a,char b);

main()

{

int n;

printf("Input the number of disks:");

scanf("%d",n);

printf("Steps of moving %d disks from A to B by means of C:\n",n);

hanoi(n,'A','B','C');

}

void hanoi(int n,char a,char b,char c)

{

if(n == 1)

move(n,a,b);

else

{

hanoi(n-1,a,c,b);

move(n,a,b);

hanoi(n-1,c,b,a);

}

}

void move(int n,char a,char b)

{

printf("Move %d:from %c to %c\n",n,a,b);

}

//给你参考一下。

汉诺塔c语言程序代码输出移动次数(c语言汉诺塔游戏)  第1张

c语言证明汉诺塔次数公式

c语言证明汉诺塔次数公式:f(k+1)=2*f(k)+1来计算。

#includestdio.h

usingnamespacestd

#defineMOD1000000

longlongcal(longlonga,intn,intm)

longlongans=1

a=a%m

while(n)

ans=(ans*a)%m

n=n1

a=(a*a)%m;//

returnans;

intmain(void)

intn,i,m,ans

scanf("%d",n)

while(n——)

scanf("%d",m)

printf("%lld\n",cal(2,m,MOD)-1)

return0

分析

来说明一个现象,假如A柱子上有两个大小相同的盘子,上面一个是黑色的,下面一个是白色的,我们把两个盘子移动到B上,需要两次,盘子顺序将变成黑的在下,白的在上,然后再把B上的盘子移动到C上,需要两次,盘子顺序将与A上时相同,由此我们归纳出当相邻两个盘子都移动偶数次时,盘子顺序将不变,否则上下颠倒。

c语言编写的这个汉诺塔问题,只能算出31以内的圆盘的个数的移动次数,如何算出更多圆盘的移动次数?

应该是超过31时,数据超过了int的取值范围,换成double或者float

#include stdio.h

float toh(int x)          //汉诺塔实现程序,主要应用函数的递归调用

{

float f;

if(x==1) return f=1.0;

else return f=2*toh (x-1)+1;     //函数的递归调用

}

main()                //主函数

{

   int  n;

   float times;                 //定义圆盘的个数,和次数

   printf("N:");

   scanf("%d",n);

   times=toh(n);                 //函数的调用

   printf("%f\n",times);

}

以上内容为新媒号(sinv.com.cn)为大家提供!新媒号,坚持更新大家所需的互联网后端知识。希望您喜欢!

版权申明:新媒号所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流,不声明或保证其内容的正确性,如发现本站有涉嫌抄袭侵权/违法违规的内容。请发送邮件至 k2#88.com(替换@) 举报,一经查实,本站将立刻删除。

(0)
上一篇 2023-09-23 13:43
下一篇 2023-09-23 13:43

相关推荐

发表回复

登录后才能评论