sum+=n * factorial(n-1); 这一步函数递归调用的思路int factorial(int n){int sum=0;if(n==1)sum=1;elsesum+=n * factorial(n-1);return sum;}void main(){int i=5;printf("5's factorial is %d\n",factorial(i));}
来源:学生作业帮助网 编辑:六六作业网 时间:2024/12/25 16:38:16
sum+=n * factorial(n-1); 这一步函数递归调用的思路int factorial(int n){int sum=0;if(n==1)sum=1;elsesum+=n * factorial(n-1);return sum;}void main(){int i=5;printf("5's factorial is %d\n",factorial(i));}
sum+=n * factorial(n-1); 这一步函数递归调用的思路
int factorial(int n)
{
int sum=0;
if(n==1)
sum=1;
else
sum+=n * factorial(n-1);
return sum;
}
void main()
{
int i=5;
printf("5's factorial is %d\n",factorial(i));
}
sum+=n * factorial(n-1); 这一步函数递归调用的思路int factorial(int n){int sum=0;if(n==1)sum=1;elsesum+=n * factorial(n-1);return sum;}void main(){int i=5;printf("5's factorial is %d\n",factorial(i));}
第1次:factorial(5)
sum += 5 * factorial(4)
第2次:factorial(4)
sum += 4 * factorial(3)
第3次:factorial(3)
sum += 3 * factorial(2)
第4次:factorial(2)
sum += 2 * factorial(2)
第5次:factorial(1)
sum = 1
第4次:factorial(2)
sum += 2 * 1 = 2
第3次:factorial(3)
sum += 3 * factorial(2) = 3 * 2 = 6
第2次:factorial(4)
sum += 4 * factorial(3) = 4 * 6 = 24
第1次:factorial(5)
sum += 5 * factorial(5) = 5 * 24 = 120
第1次: factorial(5)
sum += 5 * factorial(4)
第2次: factorial(4)
sum += 4 * factorial(3)
第3次: factorial(3)
sum += 3 * factorial(2)
第4次: factorial(2)
sum += 2 * factorial(2)
第5次: factorial(1)
sum = 1