是什么导致Java(冰雹序列)在我的程序中崩溃 [英] What's causing Java (hailstone sequence) to crash in my program
问题描述
我做了一个程序来执行(通常称为)hailstone序列,该程序基本上是这样做的:
创建一个 int
(value)并为其赋值。
creates an int
(value) and assign it a value.
如果int是偶数,则除以2。
If the int is even, divide it by two.
如果int是奇数,则将其乘以3并加1。继续这个过程,直到n等于一。
If the int is odd, multiply it by three and add one. Continue this process until n is equal to one.
它似乎与大多数数字一起工作正常,但这个数字99888769,应用程序挂起一个负整数。这是为什么?他们说没有人能够证明它停止了,我没想到我已经解决了这个问题。但知道为什么我的应用停止会很有趣。 -
private void hailStoneSequence(){
int value = 99888769;
int i = 0;
boolean trueOrFalse = isOddOrEven (value);
while (value != 1){
while (trueOrFalse == true && value != 1){
i++;
int previousValue = value;
value = value / 2;
println( previousValue +" is even, so I take half: "+value);
trueOrFalse = isOddOrEven (value); // returning true or false, and inserting the newly divided number. So that it breaks loop when nescesary.
}
while (trueOrFalse == false && value != 1){
i++;
int previousValue = value;
value = (value * 3) + 1;
println (previousValue +" is odd, so I make 3n+1: "+value);
trueOrFalse = isOddOrEven (value);
}
}
println ("\n\nThe process took "+i+" to reach "+value);
}
private boolean isOddOrEven(int value){
/*
* Takes an value and returns true, if that number is even.
* Else it returns false.
*/
if (value % 2 != 0){
return false;
}else{
return true;
}
}
}
推荐答案
随着你不断增加 int
s,他们最终会(看起来像一个惊人的行为)变成负面因为你超过了int类型的最大值(2 ^ 31-1),即你最终改变了用于存储数字符号的位(int的二进制表示)。请改用 long
。
As you keep increasing int
s, they will eventually (in what might seem like a startling behavior) become negative because you are surpassing the maximum value of the int type (2^31-1), i.e. you end up changing the bit (of the int's binary representation) that is used to store the sign of the number. Use long
instead.
这篇关于是什么导致Java(冰雹序列)在我的程序中崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!