我知道递归是一种在函数本身内部调用函数的技术。
但是下面的代码让我对第一次递归后如何执行 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/