java:for循环在BigInteger的情况下如何工作
我想将用户的输入作为大整数并将其操纵到 For 循环中,
BigInteger i;
for(BigInteger i=0; i<=100000; i++) {
System.out.println(i);
}
但它不会起作用,
任何人都可以帮助我。
I want to take Input from the user as Big-Integer and manipulate it into a For loop
BigInteger i;
for(BigInteger i=0; i<=100000; i++) {
System.out.println(i);
}
But it won't work
can any body help me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以改用这些语法:
下面是一个将它们放在一起的示例:
请注意,使用 BigInteger 作为循环索引是非常不典型的。
long
通常足以满足此目的。API 链接
java.math.BigInteger
int CompareTo(BigInteger val)
来自接口可比较
BigInteger 减法(BigInteger val)
BigInteger add(BigInteger val)
静态BigInteger valueOf(long val)
compareTo
习惯用法来自文档:
换句话说,给定
BigInteger x, y
,这些是比较习惯用法:这不是特定于
BigInteger
;这适用于任何Comparable< /code>
一般来说。
关于不可变性的注意事项
BigInteger
与String
一样,是一个不可变的对象。初学者往往会犯以下错误:由于它们是不可变的,因此这些方法不会改变它们所调用的对象,而是返回新对象,即这些操作的结果。因此,正确的用法是这样的:
You use these syntax instead:
So here's an example of putting it together:
Note that using
BigInteger
as a loop index is highly atypical.long
is usually enough for this purpose.API links
java.math.BigInteger
int compareTo(BigInteger val)
frominterface Comparable<T>
BigInteger subtract(BigInteger val)
BigInteger add(BigInteger val)
static BigInteger valueOf(long val)
The
compareTo
idiomFrom the documentation:
In other words, given
BigInteger x, y
, these are the comparison idioms:This is not specific to
BigInteger
; this is applicable to anyComparable<T>
in general.Note on immutability
BigInteger
, likeString
, is an immutable object. Beginners tend to make the following mistake:Since they're immutable, these methods don't mutate the objects they're invoked on, but instead return new objects, the results of those operations. Thus, the correct usage is something like:
好吧,首先,你有两个名为“i”的变量。
其次,用户输入在哪里?
第三, i=i+i 将 i 拆箱为一个原始值,可能会溢出它,并将结果装箱到一个新对象中(也就是说,如果该语句甚至可以编译,我还没有检查)。
第四,i=i+i 可以写成 i = i.multiply(BigInteger.valueof(2))。
第五,循环永远不会运行,因为 100000 <= 1 是假的。
Well, first of all, you have two variables called "i".
Second, where's the user input?
Third, i=i+i unboxes i into a primitive value, possibly overflowing it, and boxes the result in a new object (that is, if the statement even compiles, which I haven't checked).
Fourth, i=i+i can be written as i = i.multiply(BigInteger.valueof(2)).
Fifth, the loop is never run, because 100000 <= 1 is false.
我认为这段代码应该可以工作
I think this code should work
这可以工作
(或)
注意不要声明 BigInteger 两次。
This could work
(or)
Note that don't declare BigInteger twice.
这是为了按升序运行循环:
This is for running the loop in ascending order: