簡體   English   中英

Java while循環嵌套在for循環中。

[英]Java while loop nested in a for loop.

我有一個我不理解的簡單代碼示例。

// Compute integer powers of 2.

class Power {
    public static void main (String args[]) {
        int e, result;

        for (int i = 0; i < 10; i++) {
            result = 1;
            e = i;
            while (e > 0) {
                result *= 2;
                e--;
            }
            System.out.println("2 to the " + i + " power is " + result);
        }
    }
}

產生此輸出。

2 to the 0 power is 1
2 to the 1 power is 2
2 to the 2 power is 4
2 to the 3 power is 8
2 to the 4 power is 16
2 to the 5 power is 32
2 to the 6 power is 64
2 to the 7 power is 128
2 to the 8 power is 256
2 to the 9 power is 512

問題:

  1. result為什么不總是為2,因為每次進入for循環都會重新初始化它?

  2. 電子減額也e-- ,不是嗎? 由於再次e被設置為i重新在每個迭代上。

謝謝。

結果為什么不總是為2,因為每次進入for循環都會重新初始化它?

是的,它僅在第一個循環中被重新初始化。 您的內部循環正在循環while(e > 0)並在每次迭代中將結果翻倍。 然后,一旦完成循環,就可以預載結果並重新啟動。 result的值將取決於e ,后者定義了將result加倍的次數。

電子減額也無濟於事,不是嗎? 再一次,由於每次迭代都將e重新設置為等於i。

同樣,是的,它在每次迭代時都被設置回i,但這並不意味着它沒有用。 在每次迭代中,將e設置回新的i值,然后使用它創建一個內部循環, while e > 0 ,其中在每次迭代中,將e減1並將結果加倍。

這兩個問題在一起。

您會看到,e設置為i,每次迭代實際上都會增加。 e越高,內部經歷的時間就越頻繁。

因此,例如在您的第3個迭代中

i = 2
e = 2
result = 1

所以首先:

result = result*2 = 1*2 = 2
e = 1

e仍然> 0,因此在第二次之后:

result = result*2 = 2*2 = 4
e = 0

然后我們走了。

e--做了兩次,結果不是2。

resultefor循環的頂部重新初始化,但在while循環內修改,然后將result顯示在for循環的底部。

暫無
暫無

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

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