[英]I don't understand what is wrong with my logic that is making some of my output come out correct and incorrect
[英]My output is correct but i don't understand my output
这是我的代码:
#include<stdio.h>
int move_disks(int, char, char, char);
int main()
{
int num;
char a='A',b='B',c='C';
printf("Enter the number of disk: ");
scanf("%d",&num);
printf("\nThe sequence of movement of disks are:\n");
move_disks(num, a, b, c);
return 0;
}
int move_disks(int num, char source_peg, char aux_peg, char to_peg)
{
if(num == 1)
{
printf("\nMove disk 1 from peg %c to peg %c.", source_peg, to_peg);
return;
}
move_disks(num - 1, source_peg, to_peg, aux_peg);
printf("\nMove disk %d from peg %c to peg %c.", num, source_peg, to_peg);
move_disks(num - 1,aux_peg, source_peg, to_peg);
}
我的 output 是这样的:
Enter the number of disk: 3
The sequence of movement of disks are:
Move disk 1 from peg A to peg C.
Move disk 2 from peg A to peg B.
Move disk 1 from peg C to peg B.
Move disk 3 from peg A to peg C.
Move disk 1 from peg B to peg A.
Move disk 2 from peg B to peg C.
Move disk 1 from peg A to peg C.
在 output 中,行“将磁盘 1 从挂钩 C 移动到挂钩 B”。 我不明白这是怎么发生的,因为在我的递归代码 function 中,if 语句“printf(”\n将磁盘 1 从 peg %c 移动到 peg %c。”,source_peg,to_peg);” 这是打印语句,在任何递归调用中,我从不将“peg C”作为源 peg 传递。
main
function 的初始呼叫是
move_disks(num, a, b, c);
在这里,您将c
作为函数的to_peg
参数传递。
在你做的第一个递归调用中
move_disks(num - 1, source_peg, to_peg, aux_peg);
这里to_peg
作为aux_peg
传递给递归调用。
稍后你会打电话给:
move_disks(num - 1,aux_peg, source_peg, to_peg);
您将aux_peg
用作递归调用的source_peg
的位置。
所以在几次调用之后c
peg 确实会成为源( c
-> to_peg
, to_peg
-> aux_peg
, aux_peg
-> source_peg
)。
如果您学习了如何使用调试器逐个语句地调试代码,同时监视变量及其值,那么所有这些都应该非常清楚。
我还建议在调试时使用笔和纸,以便更容易跟进。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.