任何人都可以跟踪此程序以帮助我更好地了解递归的工作原理

时间:2018-12-03 23:40:24

标签: c++ recursion

该程序解决了河内之塔难题。难题的目的是遵循以下简单规则将一整堆磁盘移动到另一根杆上:

一次只能移动一个磁盘。 每一步都包括从一个纸堆中取出上盘并将其放在另一个纸堆的顶部或空杆上。 请勿将较大的磁盘放置在较小的磁盘上。 使用3个磁盘,可以通过7个动作解决难题。解决“河内之塔”难题所需的最小移动数为2 ^ n − 1,其中n是磁盘数。

#include <stdio.h>
void tower(int n, char start, char end, char help)
{
    if (n == 0)
    {
        return;
    }
    tower(n - 1, start, help, end);
    printf("\nDisk %d has been moved from tower %c to tower %c", n, start, 
    end);
    tower(n - 1, help, end, start);
}

int main()
{
    tower(3, 'A', 'C', 'B');
    return 0;
}`

1 个答案:

答案 0 :(得分:2)

在许多环境中,通过调试器运行只是不可用。在特定的嵌入式系统中,或在生产中运行 N 天的作业之前,会发生错误。

在这些情况下,使用简单的printf()或更复杂的日志记录功能记录程序流可能是确定发生了什么的唯一方法之一。

与跟踪执行的递归流程类似,只需在函数中添加打印:

void tower(int n, char start, char end, char help)
{
    printf("tower(n=%d, start=%c, end=%c, help=%c)\n", n, start, end, help);
    ...

给予:

tower(n=3, start=A, end=C, help=B)
tower(n=2, start=A, end=B, help=C)
tower(n=1, start=A, end=C, help=B)
tower(n=0, start=A, end=B, help=C)
Disk 1 has been moved from tower A to tower C
tower(n=0, start=B, end=C, help=A)
Disk 2 has been moved from tower A to tower B
tower(n=1, start=C, end=B, help=A)
tower(n=0, start=C, end=A, help=B)
Disk 1 has been moved from tower C to tower B
tower(n=0, start=A, end=B, help=C)
Disk 3 has been moved from tower A to tower C
tower(n=2, start=B, end=C, help=A)
tower(n=1, start=B, end=A, help=C)
tower(n=0, start=B, end=C, help=A)
Disk 1 has been moved from tower B to tower A
tower(n=0, start=C, end=A, help=B)
Disk 2 has been moved from tower B to tower C
tower(n=1, start=A, end=C, help=B)
tower(n=0, start=A, end=B, help=C)
Disk 1 has been moved from tower A to tower C
tower(n=0, start=B, end=C, help=A)

还有方便的编译器宏__FILE____FUNCTION____LINE__(还有更多,取决于您的编译器)。可以嵌入到日志/打印语句中的

printf( "Something eldritch happened in %s at %s:%d\n", __FUNCTION__, __FILE__, __LINE__ );