【问题标题】:Can someone explain to me why my factorial recursion code can't be compiled有人可以向我解释为什么我的阶乘递归代码无法编译吗
【发布时间】:2020-06-11 10:09:23
【问题描述】:

我做了一个简单的程序来计算一个数的阶乘。下面是代码。

#include <stdio.h>

int factorial(int i);

int main(void)
{
    int i;
    printf("Factorial of: ");
    scanf("%i", &i);
    printf("Answer: %i\n", factorial(i));

}

int factorial(int i)
{
    if (i == 0)
    {
        return 1;
    }

    factorial(i) = (factorial(i - 1) * i);
    return factorial(i);
}

编译器告诉我以下行有问题

factorial(i) = (factorial(i - 1) * i);

所以我将上面的行更改为以下行并且它起作用了

int a = (factorial(i - 1) * i);
return a;

那么,有人可以向我解释为什么 (factorial(i) = (factorial(i - 1) * i);) 的初始行不起作用吗?

【问题讨论】:

  • 在您看来,这条线是什么意思?
  • 你不能给函数的返回值赋值。那没有意义。将最后两行替换为return factorial(i - 1) * i;
  • factorial(i) 返回一个整数。 factorial(i) = thing; 会调用factorial(i),获取返回值,然后立即用thing 覆盖它。没有太大意义
  • 我已经阅读了大家的回复,非常感谢您的帮助。基本上,我所做的没有意义。我正在调用一个返回值的函数并将其分配给返回值的同一函数。这是一团糟。
  • ".. 编译器告诉我以下行有问题。" [需要引用] 包括它报告的确切文本

标签: c recursion factorial


【解决方案1】:
factorial(i) = (factorial(i - 1) * i);

此行在 C 标准方面无效。它与lvaluervalue 定义有关。

lvalue - 是一个引用对象的表达式。名称“左值”来自赋值表达式E1 = E2,其中左操作数E1 必须是lvalue 表达式。

rvalue - 是一个不是lvalue 的表达式(我找不到它的确切定义)。换句话说,rvalue 不能被重新分配。

例子:

int n;
...
n = 3; // --> Legal, n is an lvalue and 3 is an rvalue
3 = n; // --> illegal, 3 is rvalue and thus n cannot be assigned to it

另一个例子

int a, b, c;
...

a = b + c; // --> Legal since 'a' is an lvalue (refers to an object/memory)
/* Note that 'b' is also lvalue, 'c' is also lvalue BUT 'b + c' is an rvalue expression! */
/* the temporal storage allocated for the result of the expression 'b + c' cannot be "visible" */
/* one cannot check the address of such expression: &(a + b) ==> illegal */
b + c = a; // --> Illegal

在您的示例中,factorial(i) 表示函数的返回值,即rvalue

更多详情: https://www.embedded.com/lvalues-and-rvalues/

【讨论】:

    【解决方案2】:

    factorial(i) = (factorial(i - 1) * i);

    您试图在函数调用时分配一个整数。当您编写factorial(i) 时,您是在告诉系统调用函数阶乘并返回一个值。您不能为该值分配值。

    【讨论】:

      【解决方案3】:

      因为在这个sn-p

          factorial(i) = (factorial(i - 1) * i);
          return factorial(i);
      

      在所有提到factorial(i) 的地方,它总是被解释为试图再次调用该函数。

      为了解决这个问题,引入一个临时变量:

          int result = (factorial(i - 1) * i);
          return result;
      

      【讨论】:

        【解决方案4】:

        仅仅是因为你不能给 C 中的函数调用赋值。 factorial(i) 调用该函数(顺便说一句,这会导致无限递归)并且您试图为该调用分配一个值,这是不可能的。在其他一些语言中,这是返回值的方式,但在 C 中不是。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-04-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多