我的简单阶乘计算器c++程序出错了吗?
Am I doing something wrong with my simple factorial calculator C++ program?
半个小时前,我做了一个简单的阶乘计算器,它接受非零整数作为输入。在测试了一些值之后,我注意到它只能正常工作到12!
我已经几个月没有编程了,老实说,我还是个初学者。我决定使用递归,这样我就可以更快地回到"编程模式"(我的首选)。
我检查和修改了将近一个小时。我真不知道我的算法出了什么问题。
这是我的代码:
#include <iostream>
using namespace std;
int factorial(int);
int main()
{
int usrInput = 0; //initialize input variable
cout << "Please input the factorial you want to calculate: ";
cin >> usrInput;
while(usrInput < 1)
{
cout << "Please input a valid number: ";
cin >> usrInput;
} //end while
cout << "nAnswer: " << factorial(usrInput) << 'n';
return 0;
}
int factorial(int n)
{
int product = n;
if(n < 2)
product = 1;
else
{
product *= factorial(n-1);
cout << "n" << product; //debugging line
} //end if else
return product;
}
您超出了int的限制。13 != 6227020800, int只包含-2147483648 ..2147483647. 使用更大的字体(例如:__int64), double(但你会失去精度)或实现(或使用)大数库。
相关文章:
- #定义c-预处理器常量..我做错了什么
- 努力将整数转换为链表。不知道我在这里做错了什么
- 首要问题的答案让值班员搞错了
- 看起来is_nothrow_constructible_v()在MSVC中被破坏了,我错了吗
- .h 和.cpp文件分离时出错,但仅使用 .h 文件时没有错误.我做错了什么?
- 我的C++线程做错了什么?
- 如何正确使用 >=?(a+f()+c)>=0 错了吗?
- 谁能告诉我我用 getline 做错了什么 (cpp) 格式
- 没有输出的合并排序我做错了什么?
- 我正在尝试使用 while 循环从字符串中删除字母,直到没有字母。我在这里做错了什么?
- 在C++中使用 AKS 素数测试计算双胞胎素数 我做错了什么?
- 指针相关的UE4崩溃.我的指针哪里错了?
- 我一直试图弄清楚我在这个链表程序中做错了什么
- 我正在尝试学习如何在 c++ 中传递指针,但出现错误:没有用于调用"test"的匹配函数。我做错了什么?
- FFMPEG,C++,内存泄漏,我做错了什么?
- 我做错了什么?反向字符串 C++
- 我在这个课上做错了什么?
- 我在尝试将多个值push_back向量时出错。我做错了什么?
- 过载时出错 <<。我在这里做错了什么?
- 使用针对Win32的英特尔C++编译器编译Qt时出错,我做错了什么