[英]Why does the loop ignore multiples of five?
I've just started learning Java, so my question is probably incredibly stupid.我刚刚开始学习 Java,所以我的问题可能非常愚蠢。
I'm trying to solve one of the simpliest problems.我正在尝试解决最简单的问题之一。
Modify the previous program such that only multiples of three or five are considered in the sum, eg 3, 5, 6, 9, 10, 12, 15 for n=17修改之前的程序,使得和中只考虑三或五的倍数,例如 3, 5, 6, 9, 10, 12, 15 for n=17
Here is my code:这是我的代码:
import java.util.Scanner;
public class NewProblem {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
for (int i = 0; i < n; i++) {
if (i % 5 == 0 || i % 3 == 0) {
System.out.println(i);
}
else {
i++;
}
}
}
}
When I run it, it's showing only multiples of three.当我运行它时,它只显示三的倍数。 For example, here is the output for n = 17:例如,这里是 n = 17 的输出:
0 3 6 9 10 15 0 3 6 9 10 15
So it just ignores all multiples of 5.所以它只是忽略了 5 的所有倍数。
What's wrong?怎么了? Sorry again if the question is really stupid.如果问题真的很愚蠢,再次抱歉。
The problem here is the else
statement, which will add one to "i" if it's not divisble by 3
or 5
.这里的问题是else
语句,如果 "i" 不能被3
或5
整除,它会将 1 加到 "i" 上。 Now, let's see what your method does if n = 5
.现在,让我们看看当n = 5
你的方法会做什么。 First, the for loop runs with 0
, which is divisble by 5
and 3
, so the for
loop runs again and now i = 1
.首先,for 循环以0
运行,它可以被5
和3
整除,所以for
循环再次运行,现在i = 1
。 1
is not divisible by 5
or 3
, so the else
statement is called, adding 1
to i
, but since you have already set the for
loop to do this, it will effectively add 2
to i
, skipping i = 2
, and you don't notice, because 2
shouldn't be printed out in the first place. 1
不能被5
或3
整除,因此调用else
语句,将1
添加到i
,但由于您已经设置了for
循环来执行此操作,因此它将有效地将2
添加到i
,跳过i = 2
,并且您不会不要注意,因为2
不应该首先打印出来。 Then i = 3
, the if
statement fires printing out like normal, the for
loop fires again and this time i = 4
.然后i = 3
, if
语句像平常一样触发打印, for
循环再次触发,这次i = 4
。 And 4
is not divisible by 3
or 5
, so the else
statement fires again effectively adding 2
to i
since the for
loop adds one and the else statement one, resulting in i = 6
, skipping i = 5
.并且4
不能被3
或5
整除,因此else
语句再次触发,有效地将2
添加到i
因为for
循环添加 1 和 else 语句添加 1,导致i = 6
,跳过i = 5
。 This is where the problem lies.这就是问题所在。 Since the for
loop already adds one to i
every time it loops (the last section of the for
statement says i++
) resulting in some numbers being skipped.由于for
循环在每次循环时都会向i
添加一个( for
语句的最后一部分说i++
)导致一些数字被跳过。 Simply remove the else
statement and your code should work fine.只需删除else
语句,您的代码应该可以正常工作。
您不需要在 else 块中增加 i ,它会在 for 循环的每次迭代中增加。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.