簡體   English   中英

為什么這個while循環會導致無限循環?

[英]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 ,你有一個無限循環。

如果Collat​​z猜想為真,那么循環總是會達到1 - 問題是你不能停止循環1 :)

while (input >= 1)更改為while (input > 1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM