28

我想将用户的输入作为 Big-Integer 并将其操作到 For 循环中

BigInteger i;
for(BigInteger i=0; i<=100000; i++) {
    System.out.println(i);
}

但它不会工作

有谁能够帮助我。

4

5 回答 5

55

您可以改用以下语法:

BigInteger i = BigInteger.valueOf(100000L);  // long i = 100000L;
i.compareTo(BigInteger.ONE) > 0              // i > 1
i = i.subtract(BigInteger.ONE)               // i = i - 1

所以这里有一个把它放在一起的例子:

    for (BigInteger bi = BigInteger.valueOf(5);
            bi.compareTo(BigInteger.ZERO) > 0;
            bi = bi.subtract(BigInteger.ONE)) {

        System.out.println(bi);
    }
    // prints "5", "4", "3", "2", "1"

请注意,BigInteger用作循环索引是非常不典型的。long通常足以达到此目的。

API 链接


compareTo成语_

从文档中:

此方法优先于六个布尔比较运算符 ( <, ==, >, >=, !=, <=) 中的每一个的单独方法提供。执行这些比较的建议习惯用法是: ( ),其中是六个比较运算符之一。x.compareTo(y)<op>0<op>

换句话说,给定BigInteger x, y,这些是比较成语:

x.compareTo(y) <  0     // x <  y
x.compareTo(y) <= 0     // x <= y
x.compareTo(y) != 0     // x != y
x.compareTo(y) == 0     // x == y
x.compareTo(y) >  0     // x >  y
x.compareTo(y) >= 0     // x >= y

这不是特定于BigInteger; 这适用于任何Comparable<T>一般情况。


关于不变性的注意事项

BigInteger, 就像String, 是一个不可变的对象。初学者容易犯以下错误:

String s = "  hello  ";
s.trim(); // doesn't "work"!!!

BigInteger bi = BigInteger.valueOf(5);
bi.add(BigInteger.ONE); // doesn't "work"!!!

由于它们是不可变的,因此这些方法不会改变调用它们的对象,而是返回新对象,即这些操作的结果。因此,正确的用法是这样的:

s = s.trim();
bi = bi.add(BigInteger.ONE);
于 2010-06-11T15:46:31.093 回答
3

嗯,首先,你有两个变量叫做“i”。

其次,用户输入在哪里?

第三, i=i+i 将 i 拆箱成一个原始值,可能会溢出它,并将结果装箱到一个新对象中(也就是说,如果该语句甚至可以编译,我还没有检查过)。

第四,i=i+i 可以写成 i = i.multiply(BigInteger.valueof(2))。

第五,循环永远不会运行,因为 100000 <= 1 是假的。

于 2010-06-11T15:59:48.580 回答
1

我认为这段代码应该可以工作

public static void main(String[] args) {
    BigInteger bigI = new BigInteger("10000000");
    BigInteger one = new BigInteger("1");

    for (; bigI.compareTo(one) == 0; bigI.subtract(one)) {
       bigI = bigI.add(one);
    }
}
于 2010-06-11T15:52:58.513 回答
1

这可以工作

BigInteger i;
        for(i = BigInteger.valueOf(0);i.compareTo(new BigInteger("100000")) 
            <=0;i=i.add(BigInteger.ONE))
        {
            System.out.println(i);
        }

(或者)

for(BigInteger i = BigInteger.valueOf(0);i.compareTo(new BigInteger("100000")) 
            <=0;i=i.add(BigInteger.ONE))
        {
            System.out.println(i);
        }

请注意,不要两次声明 BigInteger。

于 2021-02-22T08:27:20.247 回答
0

这是为了按升序运行循环:

BigInteger endValue = BigInteger.valueOf(100000L);

for (BigInteger i = BigInteger.ZERO; i.compareTo(endValue) != 0; i = i.add(BigInteger.ONE)) {
   //... your logic inside the loop
}
于 2022-01-15T15:30:31.710 回答