我的简单阶乘计算器c++程序出错了吗?

Am I doing something wrong with my simple factorial calculator C++ program?

本文关键字:出错 错了 程序 c++ 简单 阶乘 计算器 我的      更新时间:2023-10-16

半个小时前,我做了一个简单的阶乘计算器,它接受非零整数作为输入。在测试了一些值之后,我注意到它只能正常工作到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(但你会失去精度)或实现(或使用)大数库。