Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/135.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 递归阶乘函数不能正常工作_C++_Recursion - Fatal编程技术网

C++ 递归阶乘函数不能正常工作

C++ 递归阶乘函数不能正常工作,c++,recursion,C++,Recursion,为什么这个递归函数最多只能计算(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 ); #包括 使用名称空间std; 长整型阶乘(长整

为什么这个递归函数最多只能计算(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 );
#包括
使用名称空间std;
长整型阶乘(长整型数)
{
如果(数字>数字)

cout因为整型long long有它能存储的最大值

#include <iostream>
#include <limits>

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

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
当一个数字大于最大值时,则行为是未定义的。在大多数计算机上发生的情况是,它环绕到最负数



它被调用。我喜欢Wiki页面中的这个里程表示例。请注意:
unsigned long
也不够。
 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
2432902008176640000    20 factorial
9223372036854775807    2^63-1 (the maximum for a long long on your computer)
51090942171709440000   21 factorial