递归 = 递推 + 回归
求 n! ,程序如下:
#include <stdio.h>
int recursion(int);
int main()
{
int x,sum;
puts("请输入一个整数:");
scanf_s("%d",&x);
sum = recursion(x);
printf("%d!= %d\n\n",x,sum);
return 0;
}
int recursion(int x)
{
if(x==0 || x==1)
return 1; //谁调用,就返回给谁
else
return x*recursion(x-1);
}
以 4! 为例:
--------->递推
recursion(4) = 4*recursion(3)
recursion(3) = 3*recursion(2)
recursion(2) = 2*recursion(1)
recursion(1) = 1 -------结束条件
recursion(2) = 2*1 ................<----------开始回归
recursion(3) = 3*2
recursion(4) = 4*6
递归是先把数据放在栈中,然后再弹出;
栈的特点:后进先出。