问题描述
#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 中有一个很好的。