c++ - 函数如何在递归后执行 Action ?

标签 c++ recursion programming-languages computer-science

我知道递归是一种在函数本身内部调用函数的技术。 但是下面的代码让我对第一次递归后如何执行 cout 部分感到困惑:

(此代码解决了汉诺塔难题)

#include <iostream>
using namespace std;

void move_rings(int n, int src, int dest, int other); 

int main(void) 
{
    int rings;                      
    cout << "Number of Rings: ";   
    cin >> rings;
    move_rings(rings, 1, 3, 2);   

    system("PAUSE");
}

void move_rings(int rings, int source, int destination, int other)
{
     if (rings == 1)
     {
        cout << "Move from " << source << " to " << destination << endl;
     }
     else    
     {
         move_rings(rings - 1, source, other, destination);
         cout << "Move from " << source << " to " << destination << endl;
         move_rings(rings - 1, other, destination, source);  
     }
}

如您所见,move_rings 函数在 if 语句之后调用自身。

当我想象这个时,我看到一个永无止境的循环......这个函数怎么可能做

cout << "Move from " << source << " to " << destination << endl; 

部分?

程序的输出是这样的:

Move from 1 to 3
Move from 1 to 2
Move from 3 to 2
Move from 1 to 3
Move from 2 to 1
Move from 2 to 3
Move from 1 to 3

最佳答案

递归一开始可能有点难以掌握。当我这样想时,它对我来说“点击”了:你有一个基本情况,这是导致递归函数不再调用自身的条件,然后你有另一部分(代码中的“else”),函数将继续被调用。 “rings == 1”条件是您的基本情况。

每次调用函数“move_rings”时都会使用较小的参数。在每个后续调用中,变量“rings”变小(因此“更接近”基本情况),直到“rings == 1”为真,然后函数停止调用自身。

希望对您有所帮助。

关于c++ - 函数如何在递归后执行 Action ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6883547/

相关文章:

c++ - QwtPlot - 设置样本期间的内存访问冲突

python - 递归阶乘计算器 RecursionError

user-interface - 用于 GUI 桌面应用程序的 Haskell 或 D?

C++:_popen 无限循环 (Windows)

c++ - 什么是 "extern linkage and with C language linkage"

c++ - 分离轴定理错误触发

python - 总和可被 k 整除的子序列数

Java 编写接受 int : k and print to screen k of "*" 的递归函数

programming-languages - 寻找可以编写代码的编程语言 "in the debugger"

programming-languages - 您对 Falcon 语言有何看法?