首页 > 解决方案 > 递归阶乘返回语句

问题描述

为什么我们用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;

  */

标签: crecursionreturn-valuefactorial

解决方案


int fact(int n)
{
    if (n >= 1)
        return n * fact(n-1);
    else
        return 1;
}

每次fact()调用该函数时,它都会运行return n * fact(n-1);语句或return 1;语句,但不能同时运行。

你打电话fact(4)进来main()。它是这样运行的:

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未达到 a,则控制权将传递回调用它的表达式。


推荐阅读