#include<iostream>
#include<Windows.h>
using namespace std;
int age(int);
int main()
{
cout<<age(5)<<endl;
system("pause");
return 0;
}
int age(int n)
{
int c;
if(n == 1)
{
c = 10;
cout<<n<<endl;
}
else c = age(n-1)+2;
return c;
}
age(5)->age(4)->age(3)->age(2)->age(1),1满足if条件,这个时候后面就没有递归了,执行age(1),执行完c = 10把值返回,返回到age(2)函数中,
同理执行age(2),返回值是12,就这么计算下去,一直执行到age(5)。
else c = age(n-1)+2;
return c;
道理跟栈一样,先进后出
if(n==1)是递归终止条件,else后面是递归的方法,你只要按照过程演算一遍就好理解了。 这就是那道算年龄的题。
计算递增数列a(n)=a(n-1)+2,a1=10