fac2.cpp

来自「压缩包里有教材<<C++模式设计-基于QT4开源跨平台开发框架&gt」· C++ 代码 · 共 44 行

CPP
44
字号
/** File fac2.cpp    factorial function computes n! for non-negative n.    Uses standard IO library. */#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;    cout << "Please enter n: " << flush;    long n;        /* long int  */    cin >> n;      /* read from stdin,                       try to convert to long */     if (n >= 0) {         long nfact = factorial(n);        if (nfact < 0) {            cerr << "overflow error: "                  << n << " is too big." << endl;        }        else {            cout << "factorial(" << n << ") = "                 << nfact << endl;        }    }    else {        cerr << "Undefined:  "             << "factorial of a negative number: " << n << endl;    }    return 0;}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?