问题及代码:
/*
*Copyright (c)2015,烟台大学计算机与控制工程学院
*All rights reserved.
*文件名称:project.cpp
*作 者:陈文青
*完成日期:2015年6月28日
*版 本 号:v1.0
*
*问题描述:求n!的函数,当用户的输入为负数,以及输入数太大时(例如大于12),使用异常处理机制予以拒绝,并给出恰当的提示。
*程序输入:
*程序输出:
*/
#include <iostream>
using namespace std;
int fac(int n)
{
int result=1;
if(n<0)
throw string("Argument cannot be negative");
else if(n>12)
throw n;
while(n)
{
result*=n;
n--;
}
return result;
}
int main( )
{
int n;
try
{
cout<<"Please input a number n to xalculte n!:";
cin>>n;
cout<<n<<"!="<<fac(n)<<endl;
}
catch(int)
{
cout<<"Exception occurred: Too large!"<<endl;
}
catch(string s)
{
cout<<"Exception occurred: "<<s<<endl;
}
return 0;
}
运行结果:
知识点总结:
一个try 可以throw多个数值
定义throw只需要说明类型即可