在 C++ 中,数字阶乘的自写代码中的错误
Error in self written code for factorial of a number in c++
请指出以下代码中的错误: #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
现场演示
相关文章:
- 将鼠标悬停在问题上时与预期">"相关的代码错误
- VI工作室代码错误无法打开输出文件主.exe
- 引入参数化构造函数后显示 LNK 2019 未解析外部符号的代码错误
- 有关矩阵的代码错误导致分段错误(内核转储)
- C++ Schannel POST 400 错误代码错误请求
- Java 本机访问代码错误:"Invalid memory access"
- 代码错误修改
- C++代码错误分配
- "_FCbuild"不能用作函数 - C/C++ 代码错误
- 我的代码错误类型警告 1 警告 C4018 和更多错误
- 代码错误(从 1 到 100 找到质数)
- OpenCV VisualStudio,C 代码错误尝试访问像素
- 当我使用的教程完全没有错误时,为什么我的代码错误
- 简单的NOOB C 输入/输出问题:代码错误
- 为什么enumProcessModules返回false值和299代码错误
- WinhttpSetoption()失败设置TLSV1.2,带有错误代码错误_internet_incorrect_ha
- 苹果安全传输代码错误
- C++ - 国际象棋主教移动代码错误
- 导入Python库时,嵌入了Python代码错误
- 编译提升C 代码错误