[英]Incrementing every other iteration of for loop (JAVA)
I want to make a for loop that adds by 1 every other iteration, as long as it doesn't reach a value higher than 5. I've tried with nested forloops but it's still nothing like it.我想制作一个 for 循环,每隔一次迭代加 1,只要它的值不超过 5。我已经尝试过嵌套 forloops,但它仍然不是这样。
Eg Given a value x=10 or x=3.例如,给定一个值 x=10 或 x=3。
For i<x && i<=5; i++
and this is where i want a value y, to be added with +1 every other (2th) time it runs the loop.这就是我想要一个值 y,每隔(第 2 次)运行循环时添加 +1 的地方。
Thanks in advance.提前致谢。
可以通过添加一个第二可变例如为此s
即0
上的每个第一和1
上的每个第二迭代。
for(int i=0, s=0; i<5; i+=s, s=-s+1)
You can use the %
(module) operator in a condition inside the loop with the index variable, like this:您可以在带有索引变量的循环内的条件中使用
%
(模块)运算符,如下所示:
// code where you initialize x and y variables
for (int i=0; i<x && i<=5; i++) {
if (i % 2 == 0) { // even values for i
y++;
}
}
In this case the loop increments y
in the first, third, fifth (.. and so on) iterations.在这种情况下,循环会在第一次、第三次、第五次(……等等)迭代中增加
y
。 If you want to increment it on the second, fourth, sixth (... and so on), then invert the condition with i % 2 != 0
如果你想在第二个、第四个、第六个(......等等)上增加它,然后用
i % 2 != 0
反转条件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.