簡體   English   中英

用於打印 3 的倍數的 while 循環

[英]a while loop for printing multiple of 3

您的程序應打印以下內容:

 0 3 6 9 12 15 18 loop ended!

這是我的代碼。 我可以知道為什么我不能做所需的輸出嗎?

int i = 0;

while(i%3 == 0 && i < 20 ) {
    System.out.print(i);
    i++;
}

System.out.print("loop ended!");

您的 while 循環中有一個條件,必須滿足 while 循環才能繼續運行。 當 i 遞增到 1 時,while 循環條件失敗,因此將停止運行,因此您的程序將只打印 0。您應該在 while 循環中使用帶有 mod 條件的 if 語句:

int i = 0;
while(i < 20) {
    if(i%3 == 0) {
        System.out.print(i + " ");
    }
    i++;
}
System.out.print("loop ended!");

i % 3 == 0 && i < 20 - 當i的值變為 1 時,此條件評估為false 。因此循環僅執行一次。

您只需要i < 20作為循環條件,並且在循環的每次迭代中,只需在i添加 3 。

int i = 0;

while(i < 20) {
   System.out.print(i + " ");
   i += 3;
}

System.out.print("loop ended!");

輸出:

0 3 6 9 12 15 18 loop ended!
public static void main(String... args) {
    int i = 0;

    do {
        System.out.print(i + " ");
    } while ((i += 3) < 20);

    System.out.print("loop ended!");
}

我提議使用 usein for循環來簡化您的代碼:

public static void main(String... args) {
    for (int i = 0; i < 20; i += 3)
        System.out.print(i + " ");

    System.out.print("loop ended!");
}

暫無
暫無

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

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