Rav*_*ven 4 c++ recursion computer-science programming-languages
我知道递归是一种在函数本身内调用函数的技术.但是下面的代码让我对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
小智 5
首先,递归可能有点难以掌握.当我这样想时,它"点击"了我:你有一个基本情况,这是导致递归函数不再调用自身的条件,然后你有另一部分(代码中的"else") ),将继续调用该函数."ring == 1"条件是您的基本情况.
每次使用较小的参数调用函数"move_rings".在每个后续调用中,变量"rings"变小(因此"靠近"基本情况),直到"rings == 1"为真,然后函数停止调用自身.
希望有所帮助.