一个用于打印3的倍数的while循环。

huangapple go评论67阅读模式
英文:

a while loop for printing multiple of 3

问题

以下是翻译好的内容:

你的程序应该打印出以下内容:

0 3 6 9 12 15 18 循环结束!

这是我的代码。我想知道为什么无法得到期望的输出?

int i = 0;

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

System.out.print("循环结束!");
英文:

Your program should print the following:

 0 3 6 9 12 15 18 loop ended!

This is my code. May I know why can't I do the desired output?

int i = 0;

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

System.out.print(&quot;loop ended!&quot;);

答案1

得分: 3

你的while循环中有一个条件,必须满足该条件才能继续运行while循环。当i增加到1时,while循环的条件不满足,因此将停止运行,所以你的程序只会打印0。相反,你应该在while循环内部使用if语句与模运算条件:

int i = 0;
while(i < 20) {
    if(i%3 == 0) {
        System.out.print(i + " ");
    }
    i++;
}
System.out.print("循环结束!");
英文:

You have a condition in your while loop that must be satisfied for the while loop to continue running. When i increments to 1, the while loop condition fails and thus will stop running, so your program will only print 0. You instead should use an if statement inside the while loop with the mod condition:

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

答案2

得分: 2

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("循环结束!");

输出:

0 3 6 9 12 15 18 循环结束!
英文:

i % 3 == 0 &amp;&amp; i &lt; 20 - this condition evaluates to false when the value of i becomes 1. So loop only executes once.

You just need i &lt; 20 as a loop condition and in each iteration of the loop, just add 3 in i.

int i = 0;

while(i &lt; 20) {
   System.out.print(i + &quot; &quot;);
   i += 3;
}

System.out.print(&quot;loop ended!&quot;);

Output:

0 3 6 9 12 15 18 loop ended!

答案3

得分: 1

public static void main(String... args) {
    for (int i = 0; i < 20; i += 3)
        System.out.print(i + " ");
    
    System.out.print("loop ended!");
}
英文:
public static void main(String... args) {
    int i = 0;

    do {
        System.out.print(i + &quot; &quot;);
    } while ((i += 3) &lt; 20);

    System.out.print(&quot;loop ended!&quot;);
}

I offer to simplify your code with usein for loop:

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

    System.out.print(&quot;loop ended!&quot;);
}

huangapple
  • 本文由 发表于 2020年10月3日 16:54:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/64182426.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定