在 C++ 中,数字阶乘的自写代码中的错误

Error in self written code for factorial of a number in c++

本文关键字:代码 错误 阶乘 C++ 数字      更新时间:2023-10-16

请指出以下代码中的错误: #include 使用命名空间标准;

 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);
 }

在编译器中,我收到错误"赋值阶乘 (0)=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
}

它的行为类似于原始示例,但不幸的是,factorial(0)factorial(1)的记忆结果必须添加 init 列表。 从factorial(0) = 1;开始会导致无限递归。 当使用值 n 调用时,此版本还会自动将任何缺失的阶乘值添加到其备忘录中,对于所有正整数 <= n 。 最重要的是,用户仍然可以自定义任何输入的记忆结果,如下所示:factorial(5) = 0;

下面是一个使用类和垃圾的示例。

#include <iostream>
#include <unordered_map>
class factorial {
    static std::unordered_map<int,int>& map() {
        static std::unordered_map<int,int> outs;
        return outs;
    }
    int n;
public:
    factorial(int n) : n(n) {}
    factorial& operator = (int out) {
        map()[n] = out;
        return *this;
    }
    operator int () const {
        if(map().count(n)) return map()[n];
        return factorial(n-1) * n;
    }
};
int main() {
    using std::cout;
    // need to set low factorial values
    // to prevent infinite recursion
    factorial(0) = 1;
    factorial(1) = 1;
    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';  // now factorial(5) is all messed up
    cout << "   ----n";
    factorial(5) = 120;            // fix factorial(5)
    cout << factorial(5) << 'n';  // worked!
}

输出:

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

现场演示