繁体   English   中英

java:在 BigInteger 的情况下 for 循环如何工作

[英]java: how for loop work in the case of BigInteger

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

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

但它不会工作

有谁能够帮我。

您可以改用这些语法:

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通常足以达到此目的。

接口链接


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>


关于不变性的注意事项

BigIntegerString一样,是一个不可变的对象。 初学者容易犯以下错误:

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);

好吧,首先,您有两个变量,称为“i”。

其次,用户输入在哪里?

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

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

第五,循环永远不会运行,因为 100000 <= 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);
    }
}

这可以工作

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。

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

BigInteger endValue = BigInteger.valueOf(100000L);

for (BigInteger i = BigInteger.ZERO; i.compareTo(endValue) != 0; i = i.add(BigInteger.ONE)) {
   //... your logic inside the loop
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM