2016-11-18 34 views
0
// factorial calculator 
    #include <iostream> 
    using namespace std; 

    long factorial (long a) 
    { 
     if (a > 1){ 

     return (a * factorial (a-1)); }//function calling itsself 
    else 
    return 0; 
    } 

    main() 
    { 
    long number = 2; 
     cout << number << "! = " << factorial (number); 

    } 

我是begginer学习对象和类。我从我的上下文中得到了一些代码,但它得到了一些错误。 如何return语句工作时其值为0放出来时将变为0是返回1个输出为2。当它返回3输出为6 4类似的是8把不同的值放在C++的回报声明中

+0

例如,请跟踪递归(或者用你的调试器)for factorial(2)',并且你会看到你的问题... –

回答

0

这里有一个计算器来计算阶乘

#include <iostream> 

using namespace std; 

int Factorial(int long long a) { 
    int long long Ans = 1; 
    for (int x = 1; x <= a; x++) { 
     Ans *= x; 
    } 

    return Ans; 
} 

int main() { 

    int Input; 
    cin >> Input; 

    if (Input > 0) { 
     cout << Factorial(Input); 
    } 
} 

从内部调用函数通常被认为是不好的做法,所以要避免它。如果您需要更大的数字,请使用long long。此外,尝试提供有关您的问题的更多信息。

+0

啊,是的,我修复了这个问题 – user7777777

+0

只是为了更多迂腐的,'阶乘((long long)INT_MAX + 1)'永远不会终止,并调用[undefined behavior](http://stackoverflow.com/a/3948518/1270789)。 –