所以我一直在尝试在 C++ 中创建一个计算数字阶乘的阶乘函数。
#include <iostream>
using namespace std;
int factorial(int& x)
{
int b=x-1;
if(x>1)
return(x*=factorial(b));
else
return 1;
}
int main()
{
int a;
cout<<"Enter the number to get factorial (and press enter):\n";
cin>>a;
factorial(a);
cout<<endl<<a;
return 0;
}
上面的代码有效,但是如果我替换这段代码
return(x*=factorial(b));
与
return(x*=factorial(x-1));
这是行不通的。 它报告一条错误消息:“从类型为‘int’的右值对类型为‘int&’的非常量引用的初始化无效”,有人可以解释一下吗,我是初学者。
最佳答案
x - 1
不是左值:它不指定存储,因此,您不能分配给/修改它。想一想:x - 1 *= <something>
没有意义。因此,将右值传递给采用非 const
的函数是非法的。引用。
关于c++ - 这段代码有什么问题 - 在 C++ 中通过引用传递值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20301125/