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
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP