java.math.BigInteger 的问题
我在方法的开头有以下代码:
BigInteger foo = BigInteger.valueOf(0);
BigInteger triNum = BigInteger.valueOf(0);
//set min value to 1*2*3*4*5*...*199*200.
BigInteger min = BigInteger.ONE;
BigInteger temp = BigInteger.ZERO;
for(int i=1; i<=200; i++)
{
temp = BigInteger.valueOf(i);
min = min.multiply(temp);
}
System.out.println(min);
while(triNum.compareTo(min) <= 0)
{
foo.add(BigInteger.ONE);
triNum = triNum.add(foo);
System.out.println("triNum: "+triNum);
}
这应该将 min 加载到值 (1 * 2 * 3 * ... * 199 * 200),然后将 triNum 设置为第一个 *三角形数字**其值大于最小值。
问题是,当我运行该方法时,我得到的只是一个终端窗口,其中有一个“triNum:0”列表,一直在屏幕上滚动......我在代码中没有看到任何内容(尽管我完全有可能做了一些错误,而且我对 math.BigInteger 有点不熟悉),这似乎又指向 BigInteger 类。有人看到我的代码中有错误吗?
...................................................... ...................................................... ......................
*三角形数字是可以通过以下方式到达的数字:1+2+3+4+5+6+7+。 ..
I have the following code at the head of a method:
BigInteger foo = BigInteger.valueOf(0);
BigInteger triNum = BigInteger.valueOf(0);
//set min value to 1*2*3*4*5*...*199*200.
BigInteger min = BigInteger.ONE;
BigInteger temp = BigInteger.ZERO;
for(int i=1; i<=200; i++)
{
temp = BigInteger.valueOf(i);
min = min.multiply(temp);
}
System.out.println(min);
while(triNum.compareTo(min) <= 0)
{
foo.add(BigInteger.ONE);
triNum = triNum.add(foo);
System.out.println("triNum: "+triNum);
}
This is supposed to load a min to a value (1 * 2 * 3 * ... * 199 * 200), and then set triNum to the first *triangle number** with a value greater than min.
Problem is, when I run the method, all I get is a terminal window with a list of "triNum: 0" ever scrolling down the screen... I don't see anything in my code (although it is completely possible I made some mistake, and I am somewhat unfamiliar with math.BigInteger), and this seems to point back to the BigInteger class. Anyone see a bug in my code?
..........................................................................................................................
*A triangle number is a number that can be reached by: 1+2+3+4+5+6+7+...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
查看
此更新
foo
吗?或者它是否创建了一个等于 foo+ BigInteger.ONE 且不再使用的对象?Look at
Does this update
foo
? Or does it create an object that's equal tofoo+ BigInteger.ONE
which is not used again?foo 始终为 0。您需要将此行:更改
为:
foo is always 0. You need to change this line:
to this:
由于 BigInteger 是不可变的,因此您需要再次将结果分配给 foo:
As BigIntegers are immutable, you need to assign the result to foo again: