如果对其不加限制,程序会一直进行下去。
//Author:PanDaoxi
#include <iostream>
using namespace std;
void story(){
cout<<"从前有座山,山里有个庙,庙里有老和尚和小和尚,老和尚给小和尚讲故事,讲了什么呢?";
getchar();
story();
return;
}
int main(){
story();
return 0;
}
如果这样不加节制的运行下去,就形成了死循环,程序会运行到系统崩溃为止。所以要实现以下效果,我们需要对它进行条件判断。
//Author:PanDaoxi
#include <iostream>
using namespace std;
int n=0;
void story(){
n++;
cout<<"(第"<<n<<"遍)从前有座山,山里有个庙,庙里有老和尚和小和尚,老和尚给小和尚讲故事,讲了什么呢?";
getchar();
if(n<10) story(); //边界条件
else cout<<"故事讲完了!"<<endl;
return;
}
int main(){
story();
return 0;
}
这就是简单的递归算法。
二、递归算法的运用
做递归算法,我们需要找到以下几点:
//Author:PanDaoxi
#include <iostream>
using namespace std;
int age(int n){
int c;
if(n==1) c=10;
else c=age(n-1)+2;
return c;
}
int main(){
cout<<age(5);
return 0;
}