[英]n! BigInteger makes a loop
我寫了這個小程序來找到n!:
public class Fattoriale {
public static void main (String[] args){
int n;
do {
n = Input.readInt("Enter an int number ( int >=0)");
while( n < 0);
long fatt = 1;
for (int i = 2; i <= n; i++){
fatta = fatt * i;
}
System.out.println(n"+!" + " = " + fatt);
現在我正在嘗試使用BigInteger重寫這個程序。 我寫過:
import jbook.util.*;
import java.math.*;
public class Fattoriale {
public static void main (String[] args){
String s = Input.readString("Enter an int number. ");
BigInteger big = new BigInteger(s);
BigInteger tot = new BigInteger("1");
BigInteger i = new BigInteger("2");
for (; i.compareTo(big) < 0; i.add(BigInteger.ONE)){
tot = tot.multiply(i);
}
System.out.println(tot);
}
}
但是BigInteger的這個程序會產生一個循環,我無法理解為什么。 我希望有人可以幫助我。 非常感謝你 ;)。 (nb。忽略輸入類,它只是我創建的用於更快輸入輸入的類)
這應該是這樣的,因為i.add(BigInteger.ONE)
不更新變量i
。
for (; i.compareTo(big) <= 0; i=i.add(BigInteger.ONE)) {
tot = tot.multiply(i);
}
有兩個變化:
<=0
而不是<0
i
以進行更新。 怎么確認?
BigInteger i = new BigInteger("2");
System.out.println(i.add(BigInteger.ONE)); // print 3
System.out.println(i); // print 2
BigInteger
是不可變的,因此除非使用=
運算符為其設置新值,否則其值不會更改。 因此,每次在循環中調用i.add(BigInteger.ONE)
,計算機將計算i + 1,然后丟棄結果。 相反,嘗試:
for (; i.compareTo(big) < 0; i=i.add(BigInteger.ONE)){
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.