|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <iostream>
#include <climits>
using namespace std;
unsigned long returnFactorial(unsigned short num)throw(const char*);
int main()
{
unsigned short num = 0;
cout<<"请输入一个整数:";
while(!(cin>>num)||(num<1))
{
cin.clear();
cin.ignore(100,'\n');
cout<<"请输入一个整数:";
}
cin.ignore(100,'\n');
try
{
unsigned long factorial = returnFactorial(num);
cout<<num<<"的阶乘值是:"<<factorial;
}
catch(const char* e)
{
cout<<e;
}
return 0;
}
unsigned long returnFactorial(unsigned short num)throw(const char*)
{
unsigned long sum = 1;
unsigned long max = ULONG_MAX;
for(int i=1;i<=num;i++)
{
sum *= i;
max /= i; //就是这个地方,为什么max /= i;就可以判断出num是否在能计算范围内。????????????????????????
}
if(max<1)
{
throw"悲催。。。该基数太大,无法在该计算机上计算出阶乘值。\n";
}
else
{
return sum;
}
} |
|