用 C++ 语言,求出可在机器上计算阶乘的整数的最大值

c++server side programmingprogramming

在这个问题中,我们需要编写一个程序,用 C++ 语言,求出可在机器上计算阶乘的整数的最大值。

一个数的阶乘是一个巨大的值,因为它是它前面所有值的乘积。而 C++ 只能使用其内置函数处理不超过某个值的大值。我们需要找到这个限制。

解决方法

我们将简单地利用数据类型的属性,即当数字超过最大值时,将返回负数。

我们将使用 long long int,它是最大的基本数据类型。

示例

#include <iostream>
using namespace std;
int calcMaxFactVal(){
   int maxVal = 1;
   long long int maxFactorial = 1;
   while (true){
      if (maxFactorial < 0)
         return (maxVal - 1);
      maxVal++;
      maxFactorial *= maxVal;
   }
   return - 1;
}
int main(){
   cout<<"The maximum value of an integer for which factorial can be
   calculated on machine is "<<calcMaxFactVal();
   return 0;
}

输出

The maximum value of an integer for which factorial can be calculated on
machine is 20

相关文章