如果我使用递归运行 C++ 程序,则显示大于 12 的数字阶乘的错误值

问题描述

我有以下 C++ 代码来查找数字的阶乘:

#include <iostream>
using namespace std;
int factorial(int n){
   if (n<=1)
   {return 1;
    
    }
    return n*factorial(n-1);
}
int main()
{
    int a;
    cout<<"Enter a no: ";
    cin>>a;
    cout<<"The value of "<<a<<"! is "<<factorial(a);

return 0;
}

它适用于高达 12 的值! 但是在它上面显示错误的值。 例如——20个!显示 -2102132736(否定的否)

,对于一些大的值,比如 50!显示0。

可能的原因是什么???

解决方法

虽然形式上溢出 int 的行为是未定义的,但对 2 的幂的数字进行模运算是一种常见的处理方式。

像 50 这样的数字!有许多因数具有 2 的大幂。这说明了您作为输出获得的零。

解决方案是使用任意精度的整数库。 Boost 中有一个很好的。