为什么我们使用return 1
来终止递归函数?是否可以将任何其他值用作默认值,例如 1。
如果我们返回 1作为函数的返回值,那么为什么 1 不返回给 main 函数。
#include<stdio.h>
int fact(int n)
{
if(n>=1)
return (n*fact(n-1));
else
return 1;
}
int main()
{
int a,ans;
scanf("%d",&a);
ans=fact(a);
printf("factorial of %d is %d ",a,ans);
return 0;
}
/*
explanation
fact(4);
if(4>=1) 4*fact(3)
if(3>=1) 4*3*fact(2)
if(2>=1) 4*3*2*fact(1)
if(1>=1) 4*3*2*1*fact(0)
if(0>=1) return 1;
*/
int fact(int n)
{
if (n >= 1)
return n * fact(n-1);
else
return 1;
}
每次调用fact()
函数时,它都会运行return n * fact(n-1);
语句或return 1;
语句,但不能同时运行两者。
你用main()
打电话给fact(4)
.这是它的运行方式:
main:
compute fact(4)
fact(4):
| 4 >= 1? Yes!
| compute 4 * fact(3)
| fact(3):
| | 3 >= 1? Yes!
| | compute 3 * fact(2)
| | fact(2):
| | | 2 >= 1? Yes!
| | | compute 2 * fact(1)
| | | fact(1):
| | | | 1 >= 1? Yes!
| | | | compute 1 * fact(0)
| | | | fact(0):
| | | | | 0 >= 1? NO!
| | | | | return 1;
| | | | +--> 1
| | | | fact(0) is 1, return 1 * 1 (--> 1)
| | | +--> 1
| | | fact(1) is 1, return 2 * 1 (--> 2)
| | +--> 2
| | fact(2) is 2, return 3 * 2 (--> 6)
| +--> 6
| fact(5) is 6, return 4 * 6 (--> 24)
+--> 24
fact(4) is 24, assign it to `ans`, print it etc
// end of main
当函数使用return
语句时(如果未达到return
,则在执行其最后一个语句后),控件将传递回调用它的表达式。
为什么我们使用"return 1"来终止递归函数
因为这应该涵盖当n
不>=1
的情况,换句话说,当n
0
时。我不认为负面n
是有效的。0!
是1
,因此它返回该值的原因。
作为函数的结束,那么为什么 1 不返回 主要功能。
如果函数被调用0
或1
forn
,则1
将返回给主函数。对于任何其他值,1
仅在递归阶乘调用中返回,并且返回给main
函数的值不是1
,而是(n*fact(n-1))
,这在这些情况下是不1
的。
return 语句在n==0
时执行。
n==0
的阶乘是 1,所以我们返回 1。
/*
explanation
fact(4);
if(4>=1) 4*fact(3)
if(3>=1) 4*3*fact(2)
if(2>=1) 4*3*2*fact(1)
if(1>=1) 4*3*2*1*fact(0)
if(0>=1) return 1; now return is default tend to multiply as we give 1 and
return has already 24 in its stack so 1*24 is returned to main()
if we give return 2; 2*24 is returned to main();
*/
我们不希望我们的最终结果受到影响,为了解决这个错误,任何乘以 1 的结果都是相同的,所以我们在递归函数中使用 1 作为返回。
实际上 return 也是一个堆栈寄存器,它在函数中调用 with 时保存临时变量,并且它通过 multiply 属性操作默认值,因为我们始终只能发送一个返回值。