我知道Java中的int範圍應該是-2^31到2^31-1。 但是當我用20運行此代碼片段:Java的int範圍?
public class Factorial {
public int factorial(int n) {
int fac=1;
for (int i=1; i<=n; i++) {
fac *= i;
System.out.println("Factorial of " + i + " is: " + fac);
}
return fac;
}
}
輸出:
Factorial of 1 is: 1
Factorial of 2 is: 2
Factorial of 3 is: 6
Factorial of 4 is: 24
Factorial of 5 is: 120
Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320
Factorial of 9 is: 362880
Factorial of 10 is: 3628800
Factorial of 11 is: 39916800
Factorial of 12 is: 479001600
Factorial of 13 is: 1932053504
Factorial of 14 is: 1278945280
Factorial of 15 is: 2004310016
Factorial of 16 is: 2004189184
Factorial of 17 is: -288522240
Factorial of 18 is: -898433024
Factorial of 19 is: 109641728
Factorial of 20 is: -2102132736
這不是從13決策意識看起來它是超出範圍和周圍擠包。怎麼了?是由於我正在使用Eclipse嗎?
雖然我認爲這是不相關的,這裏是測試代碼:
public class TestFac {
public static void main(String[] args) {
int n;
Scanner sc = new Scanner(System.in);
System.out.println("Input num you want to factorial: ");
n = sc.nextInt();
Factorial fac = new Factorial();
fac.factorial(n);
}
}
使用** long **數據類型而不是int。 – Dhinakar
您應該首先檢查階乘13的實際值,看看它是否適合0和2^31 -1。不能指責Eclipse或Java的錯誤。就像發佈的答案一樣,長時間或甚至更好的BigInteger。 –
恩,[2^31-1是2 147 483 647](https://www.google.com/search?q=2%5E31-1)和[13!是6 227 020 800](https://www.google.com/search?q=2%5E31-1)這是*更大*。 –