[英]Why does this while loop cause an infinite loop?
public void calculate(int input) {
inputField.setText("" + input);
while (input >= 1) {
if (input % 2 == 0) {
input = input / 2;
} else {
input = (input * 3) + 1;
}
output.append("" + input);
}
}
The output variable is a JTextArea and inputField is a JTextField where the user enters an integer. 输出变量是JTextArea,inputField是用户输入整数的JTextField。
I call the method and initialize the input variable here: 我在这里调用方法并初始化输入变量:
@Override
public void actionPerformed(ActionEvent e) {
input = Integer.parseInt(inputField.getText());
calculate(input);
}
}
Every time the value of input is even, it is divided by 2 so it should eventually reach 1, correct? 每当输入的值是偶数时,它除以2,所以最终应该达到1,正确吗? Then why does this while loop cause an infinite loop? 那为什么这个while循环会导致无限循环呢?
The problem is your condition - because even if you reach 1, the loop will continue. 问题是你的情况 - 因为即使你达到1,循环也会继续。 Replace while (input >= 1)
with while (input > 1)
用while (input >= 1)
替换while (input >= 1)
while (input > 1)
This gives an infinite loop because input
can never get to zero or below. 这给出了无限循环,因为input
永远不会达到零或更低。 There is no even number >=1
which when halved gives zero, and no odd number >=1
which when tripled gives -1
. 没有偶数>=1
,当减半时给出零,没有奇数>=1
,当三倍给出-1
。 So input
will always be >=1
and you have an endless loop. 所以input
总是>=1
,你有一个无限循环。
If the Collatz conjecture is true that loop will always reach 1 -- the problem is that you don't stop looping at 1 :) 如果Collatz猜想为真,那么循环总是会达到1 - 问题是你不能停止循环1 :)
Change while (input >= 1)
to while (input > 1)
. 将while (input >= 1)
更改为while (input > 1)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.