英文:
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 && i < 20 ) {
System.out.print(i);
i++;
}
System.out.print("loop ended!");
答案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 < 20) {
if(i%3 == 0) {
System.out.print(i + " ");
}
i++;
}
System.out.print("loop ended!");
答案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 && i < 20
- this condition evaluates to false
when the value of i
becomes 1. So loop only executes once.
You just need i < 20
as a loop condition and in each iteration of the loop, just add 3 in i
.
int i = 0;
while(i < 20) {
System.out.print(i + " ");
i += 3;
}
System.out.print("loop ended!");
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 + " ");
} while ((i += 3) < 20);
System.out.print("loop ended!");
}
I offer to simplify your code with usein for
loop:
public static void main(String... args) {
for (int i = 0; i < 20; i += 3)
System.out.print(i + " ");
System.out.print("loop ended!");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论