C++中可計算階乘的最大整數值


在這個問題中,我們需要建立一個程式來查詢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

更新於: 2020年10月9日

162 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.