所以我給了一個問題,告訴我要製作一個整數階乘達到30的表格。本書特別告訴我要使用BigInteger對象。 (使用BigInteger big = BigInteger.valueOf(x))然而,這樣做非常棘手,給了我一堆我不知道如何解決的錯誤。什麼時候使用BigInteger對象而不是簡單地使用double?
例如
public static BigInteger factorial(int a){
if(a == 0){
return BigInteger.valueOf(1);
}
else{
return BigInteger.valueOf(a*BigInteger.valueOf(factorial(a-1)));// this will keep giving me an error message that I need to change the value type to "long" and back and forth to BIgInteger. I've tried many different variations including where I use BigInteger.valueOf(..) to every values.
}
}
你知道使用的BigInteger對象以正確的方式?
你什麼時候會使用BigInteger而不是double?取而代之的
BigInteger.valueOf(a*BigInteger.valueOf(factorial(a-1)))
import java.math.BigInteger;
public class BigInt {
public static double factorial(int a){
if(a == 0){
return 1;
}
else{
return a* factorial(a-1);
}
}
public static void table(int a){
for(int i =0; i<=a; i++){
System.out.println(i + ", " + factorial(i));
}
}
public static void main(String[] args) {
table(30);
}
}
...並且因爲它清楚地表明你代表*整數*而非任意有理數是有用的...... –
我在[Javadoc](https)中看不到'multiply(int)'或'multiply(long)' ://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#multiply(java.math.BigInteger中))。 –