繁体   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