我写了这个小程序来寻找 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. 忽略 Input 类,它只是我创建的用于更快输入的类)
最佳答案
这应该是这样的,因为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
关于java - n! BigInteger 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24981633/