[英]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);
}
}
輸出變量是JTextArea,inputField是用戶輸入整數的JTextField。
我在這里調用方法並初始化輸入變量:
@Override
public void actionPerformed(ActionEvent e) {
input = Integer.parseInt(inputField.getText());
calculate(input);
}
}
每當輸入的值是偶數時,它除以2,所以最終應該達到1,正確嗎? 那為什么這個while循環會導致無限循環呢?
問題是你的情況 - 因為即使你達到1,循環也會繼續。 用while (input >= 1)
替換while (input >= 1)
while (input > 1)
這給出了無限循環,因為input
永遠不會達到零或更低。 沒有偶數>=1
,當減半時給出零,沒有奇數>=1
,當三倍給出-1
。 所以input
總是>=1
,你有一個無限循環。
如果Collatz猜想為真,那么循環總是會達到1 - 問題是你不能停止循環1 :)
將while (input >= 1)
更改為while (input > 1)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.