1

半小时前,我做了一个简单的阶乘计算器,它以非零整数作为输入。在测试了一些值之后,我注意到它只能在 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;
}
4

1 回答 1

1

您超出了 int 的限制。13!= 6227020800,int 仅涵盖 -2147483648 .. 2147483647。使用更大的类型(例如 __int64)、双精度(但您会失去精度)或实现(或使用)大数字库。

于 2013-01-16T11:06:15.727 回答