#include <iostream>
long factorial(long n)
{
long ans = 1;
for(long i = 2; i <= n ; i++)
{
ans = ans * i;
if (ans < 0)
{
return -1;
}
}
return ans;
}
int main()
{
using namespace std;
do
{
cout << "Please enter n (0-16): " << flush;
long n;
if (cin >> n)
{
if (n == 9999)
{
return 0;
}
}
else
{
cerr << "Enter n is not a number! " << n << endl;
continue; }
if (n > 16)
{
cerr << "Max n is 16: "
<< n << " is too big." <<endl;
continue;
}
if (n >= 0)
{
long nfact = factorial(n);
if (nfact < 0) //overflow
{
cerr << "overflow error: "
<< n << " is too big." <<endl;
}
else
{
cout << "factorial(" << n << ") = " << nfact << endl;
}
}
else
{
cerr << "Undefined: " << "factorial of a negative number: " << n << endl;
}
}while(true);
return 0;
}
n 输入 非数字 比如 : 输入a 就一直死循环输出 Please enter n (0-16): Enter n is not a number!
请大家看看 这个是怎么回事。哪里代码有错了吗 ?谢谢了