我撰寫了一個計算 2 個數字組合的方法,它適用于 n = 10 和 r = 3 的較小數字,但是當輸入 n 為 100 且 r 為 3 時,它會引發算術例外“/ by zero”
import java.util.Scanner;
public class Combination {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter n: ");
int n = scan.nextInt();
System.out.print("\nEnter r: ");
int r = scan.nextInt();
scan.close();
int ans = factorial(n) / (factorial((n-r)) * factorial(r));
System.out.print("\nThe combination is: " ans);
}
static int factorial(int num) {
for(int i = num; i>1; --i) {
num *= (i - 1);
}
return num;
}
}
但我不知道問題是什么。它適用于較小數量的 n。
uj5u.com熱心網友回復:
您正在乘以導致數字太大而無法放入整數的值。
如果您列印出回圈num內部for,您會注意到它最終會變為負數或為零。這是由于溢位。
為了您的例子n=100,并r=3甚至不long就行了。你需要使用類似的東西BigInteger。
請記住,BigInteger與使用原語相比,使用會大大減慢您的程式速度。
如果您對擁有如此大的數字不感興趣并且只是好奇為什么它不起作用,您也可以使用Math.multiplyExact(int x, int y)orMath.multiplyExact(long x, long y)如果您正在使用Java 8或更高版本。
通過使用這些方法,您將不必處理溢位的副作用,因為ArithmeticException如果結果溢位,它們將拋出。
uj5u.com熱心網友回復:
將num的資料型別從int改為double
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/382598.html
上一篇:如何在更高維度上表達遞回呼叫
