![](/img/trans.png)
[英]Am I doing something wrong with this simple #include statement in VS 2022 C++ console app?
[英]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;
}
您超出了整數限制。 13! = 6227020800,int僅覆蓋-2147483648 ..2147483647。使用更大的類型(例如__int64),double(但是會失去精度)或實現(或使用)大數字庫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.