我知道递归是一种在函数本身内调用函数的技术。 但下面的代码混淆了我它是如何能在第一递归之后做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
您是否使用了一些IDE(例如Eclipse)?如果是这样,您可以使用调试器逐步完成程序,以更好地了解发生了什么。学习如何使用调试器是一项基本技能,所以现在就开始吧。 –
谢谢你的提示,但我还是开始了编程though..I'll肯定很快 – Raven
研究它@Deanie - 请阅读[编辑权限](http://stackoverflow.com/help/privileges/edit)尤其是关于“微小的,微不足道的修改令人沮丧的部分 - 尝试在编辑时让帖子显着更好,纠正您观察到的所有问题。”特别是,请记住,除非您有2,000位代表,否则每次编辑(甚至是微不足道的,仅用于标记的编辑)都需要最多5位其他用户的投票。请进行编辑。 –