C++中一个数的阶乘自写代码的错误

C++中一个数的阶乘自写代码的错误,c++,C++,请指出以下代码中的错误: 包括 使用名称空间std int factorial(int n) { int f=1; factorial(0)=1; factorial(1)=1; while(n>=0) { f=f*factorial(n); n=n-1; } return f; } int main() { cout << factorial(5);

请指出以下代码中的错误: 包括 使用名称空间std

 int factorial(int n) {
     int f=1;
     factorial(0)=1;
     factorial(1)=1;
     while(n>=0)
     {
         f=f*factorial(n);
         n=n-1;
     }
     return f;
 }

 int main() {
     cout << factorial(5);
 }
在编译器中,我得到赋值factorial0=1的左操作数所需的错误左值


我无法理解上述错误。请解释。

您的代码确实错误。不能将函数指定给值。我猜你在找这样的东西:

#include <iostream>
using namespace std;

int Factorial(int n)
{
    if (n <= 1)
        return 1;

    return n * Factorial(n - 1);
}

int main()
{
    int number = Factorial(5);
    cout << number << endl;
}

C++不允许模式匹配函数定义。

更新:这就像周六的学校一样

#include <iostream>
#include <unordered_map>

int& factorial(int n) {
    static std::unordered_map<int,int> memo = {{0,1},{1,1}};
    if(!memo.count(n)) {
        memo[n] = n * factorial(n-1);
    }
    return memo[n];
}

int main() {
    using std::cout;

    cout << factorial(1) << '\n';  
    cout << factorial(5) << '\n';
    cout << "   ----\n";
    factorial(1) = 123456789;      // make factorial(1) better
    cout << factorial(1) << '\n';
    cout << factorial(5) << '\n';  // factorial(5) is still 120
    //                                because its value was saved
    //                                by the first factorial(5) call
}
输出:

1
120
   ----
123456789
1929912792
   ----
120

你的语法非常错误。你可能想在C++上找到一本好的书、课或教程,或者如果你已经做了,就复习一下材料。你想达到什么目标?不能将值分配给函数调用factorial0=1;你想用factorial0=1做什么;因子1=1;是这样写的:如果n首先告诉我们你的意图是什么;因为不能将函数指定给值。但是你可以给一个变量分配一个函数,例如你可以做一些事情,比如int number=factorial0;你不能给函数结果赋值,因为函数本身已经返回一个值作为结果,即int-functionint返回一个int作为结果。@Rohit Sharma非常成熟,当你不理解主题,而那些白痴只是想帮助你理解时,你可以称人们为白痴和白痴。祝你以后能以这种态度得到帮助,真的吗?你真的在帮我吗?所有人都只是简单地说,回到你的概念或语言不允许或诸如此类。。但是没有人关注语言为什么会这样做。。只有user3078414足够接近我的查询
1
120
   ----
123456789
1929912792
   ----
120