簡體   English   中英

遞歸因子函數無法正常工作

[英]Recursive factorial function not working properly

為什么這個遞歸函數最多只能計算(20!)? 當我輸入21時,它顯示意外的結果。

#include <iostream>
using namespace std;

long long int factorial( long long int number )
{
    if( number <= 1 )
        return 1;

    return number * factorial( number - 1 );

}

int main()
{
    long long int number;
    while( cin >> number )
            cout << factorial( number ) << endl; // factorial( 20 ) = 2432902008176640000
                                                 // factorial( 21 ) = -4249290049419214848 ????
    return 0;
}

階乘21是51090942171709440000 您的計算機上可以保存的簽名長的最長為2^63-1 = 9223372036854775807

2432902008176640000    20 factorial
9223372036854775807    2^63-1 (the maximum for a long long on your computer)
51090942171709440000   21 factorial

當數字大於最大值時,行為未定義。 大多數計算機上發生的事情是它包含最負數。


因為整數型long long有它可以存儲的最大值。 您可以使用以下語句獲取它

#include <iostream>
#include <limits>

int main()
{
    std::cout << std::numeric_limits<long long>::max() << std::endl;
}

這里是long long類型的階乘,只要它占用8個字節。

 0: 1 
 1: 1 
 2: 2 
 3: 6 
 4: 24 
 5: 120 
 6: 720 
 7: 5040 
 8: 40320 
 9: 362880 
 10: 3628800 
 11: 39916800 
 12: 479001600 
 13: 6227020800 
 14: 87178291200 
 15: 1307674368000 
 16: 20922789888000 
 17: 355687428096000 
 18: 6402373705728000 
 19: 121645100408832000 
 20: 2432902008176640000

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM