【问题标题】:Problems with understanding how recursion works in C理解递归在 C 中如何工作的问题
【发布时间】:2015-01-05 03:32:20
【问题描述】:

我正在从 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 函数中的参数匹配?

* 符号是否意味着 fact(n) 中的 n 现在是 3 - 1 并且它基本上表示它会重新做一遍?

【问题讨论】:

标签: c recursion


【解决方案1】:

递归是函数调用自身的过程。 在函数定义中可以看到对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)
}

Fact(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);,它被传递回我们的初始函数调用,我们的整数'a'得到值6。

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

【讨论】:

    【解决方案2】:

    只是通过你的例子来找到 3 的阶乘

    第一个电话是fact(3)

    n = 3 所以 else 条件被执行

    3 * fact(2)
    

    n = 2 所以 else 条件被执行

    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 */
    

    【讨论】:

      【解决方案3】:

      如果你从内部调用一个函数,它被称为递归。由于您返回值 从内部调用返回,该函数被评估直到它不再调用自己,即当n &lt;= 1&lt; 只是为了解释0! == 1

      它使3n越来越少,因为

      fact(n - 1) // n - 1 < n
      

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

          猜你喜欢
          • 2014-01-28
          • 2011-08-03
          • 1970-01-01
          • 2020-11-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多