《C++语言基础》实践参考——有些数的阶乘不算了

返回:贺老师课程教学链接 项目要求

【项目2-有些数的阶乘不算了】
求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;
}
上一篇:springboot中poi操作合集


下一篇:基于VLC的播放器开发