理解递归如何在C中工作的问题

时间:2015-01-04 18:40:47

标签: c recursion

我正在从 C Programming:A Modern Approach 这本书中学习C语言中的函数。它包含以下功能:

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

以下解释:

  

要了解递归的工作原理,让我们跟踪递归的执行情况   声明i = fact(3);这里发生了什么:“

fact(3) finds that 3 is not equal or less than 1, so it calls
   fact(2)which finds that 2 is not equal or less than 1, so it calls
      fact(1) which finds that 1 is equal or less than 1, so it returns 1,causing
   fact(2) to return  2 x 1 = 2, causing
fact(3) to return 3 x 2 = 6

我真的很困惑,如果它不在循环中,为什​​么它会执行所有这些操作?为什么它会使3越来越少,直到匹配if函数中的参数?

*符号是否表示事实(n)中的n现在为3 - 1,它基本上表示它会重新执行此操作吗?

4 个答案:

答案 0 :(得分:2)

递归是函数调用自身的过程。 在函数定义中,您可以看到对fact(n-1)的调用,这意味着函数本身会再次被调用。

int fact(int n) //return value is an integer, name of function is "fact", input argument is an integer named n
{
  if (n <= 1) // if the input arg equals 1, return 1
    return 1;
  else 
    return n * fact(n - 1); //else, return n (input arg of this fact) times the return value of fact(n - 1)
}

事实(3)应该返回3 * 2 * 1 = 6。 处理语句int a = fact(3)时会发生以下情况:

fact(3) //dive into this function:
{
  if (n <= 1) //n is not 1
    return 1;
  else
    return n * fact(n - 1); //now we call fact(2)
}

我们称之为事实(2):

{
  if (n <= 1) //n is not 1
    return 1;
  else
    return n * fact(n - 1); //now we call fact(1)
}

我们称之为事实(1):

{
  if (n <= 1) //n equals 1
    return 1; //return 1
  else
    return n * fact(n - 1); 
}

现在,函数fact(1)返回1到其被调用的点,即fact(2)内。 确切地说,对于语句return 2*fact(1);,它会被传递回语句return 3*fact(2);,该语句将被传递回我们的初始函数调用和我们的整数&#39; a&#39;得到值6。

我希望这让你更清楚,如果你还有问题,请随时提出。

答案 1 :(得分:1)

按照你的例子找到3的阶乘

第一个电话是fact(3)

n = 3所以其他条件被执行

3 * fact(2)

n = 2所以其他条件被执行

2 * fact(1)

n = 1现在如果条件通过,则返回1

所以放在一起

3 * fact(2)

3 * 2 * fact(1)

3 * 2 * 1 = 6

在递归中必须有退出条件,这是

if(n = 1) /* 0! = 1 So you have reached the last iteration and you are good to return */

答案 2 :(得分:0)

如果你从内部调用一个函数,它被称为递归。因为您返回值 从内部调用返回,函数将被评估,直到它不再调用自身为止,即当n <= 1<仅用于0! == 1时。

由于

,它会使3n越来越少
fact(n - 1) // n - 1 < n

答案 3 :(得分:0)

在调用fact(n-1)时发生递归。在那里再次调用函数本身,因此代码重复自身而不需要循环。参数值会更改,因为每次都使用不同的参数调用函数。

顺便说一句,*符号表示乘法。