【问题标题】:My output is correct but i don't understand my output我的输出是正确的,但我不明白我的输出
【发布时间】:2021-08-20 06:40:39
【问题描述】:

这是我的代码:

#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);

}

我的输出是这样的:

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.

在输出中,在“将磁盘 1 从 peg C 移动到 peg B”行中。我无法理解这是怎么发生的,因为在 if 语句中的递归函数代码中“printf(”\n将磁盘 1 从 peg %c 移动到 peg %c。”,source_peg,to_peg);"这是打印语句,在任何递归调用中,我从不将“peg C”作为源 peg 传递。

【问题讨论】:

  • 谷歌河内塔,你会发现大量的信息。

标签: c dynamic-programming towers-of-hanoi


【解决方案1】:

您从main 函数发出的初始调用是

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 挂钩确实会成为源(c -> to_pegto_peg -> aux_pegaux_peg -> source_peg)。


如果您学习了如何使用调试器在监控变量及其值的同时逐条执行代码语句,那么所有这些都应该非常清楚。

我还建议在调试时使用笔和纸,以便更容易理解。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-22
    • 2020-02-09
    • 2019-11-23
    • 2022-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多