[英]What's the easiest way to increment a value by x
I have a for loop with length 20. 我有一个长度为20的for循环。
I have a height of 800. I want to put a value 20 times separated by the same gap. 我的身高是800。我想将值乘以20乘以相同的间隔。
For example: 例如:
800 / 20 = 40 800/20 = 40
Every 40 I want to println the value. 我想每打印40个值。 40, 80, 120, 160... until 800. 40、80、120、160 ...直到800。
I don't understand how to do this inside a loop. 我不知道如何在循环中执行此操作。 My approach is wrong and does not have the same gap between them. 我的方法是错误的,两者之间没有相同的差距。
for (int i = 0; i < array.size(); i++) {
int posY = (i != 0) ? 800/ i : 800;
println(posY);
}
Well there are imho three different aproaches. 好吧,恕我直言,有三种不同的方式。 Which one depends on what else you need to do with i. 哪一个取决于您还需要对i做些什么。
1) Use i directly: 1)直接使用i:
for (int i = 40; i <= 800; i+=40) {
println(i);
}
This asumes that you don't need nothing else but the 20 numbers. 假设您只需要20个数字就可以了。
2) you need to count: 2)您需要计算:
for (int i = 1; i <= 20; i++){
println(i*40);
}
2b) application eg. 2b)应用例如 if 800 is in a variable: 如果800在变量中:
for (int i = 1; i <= 800/40; i++){
println(i*40);
}
This assumes you need to track which step you are taking and want to do something with i. 假设您需要跟踪要采取的步骤,并想对i进行操作。
3) you need the steps inbetween for something 3)您需要一些中间步骤
for (int i = 1; i <= 800; i++) {
if(0 == i%40 ){ //if the rest of i/40 gives 0
println(i);
}
}
This last version prints the same numbers but still i goes over all values inbetween. 这最后一个版本打印相同的数字,但我仍然遍历它们之间的所有值。
Plus if you have an array you need to iterate over: replace the 800 with "array.length -1" 另外,如果您有数组,则需要迭代:用“ array.length -1”替换800
OR replace the "<=" by "<" and use "array.length" above. 或将“ <=“替换为“ <”,并使用上面的“ array.length”。
(And well there are a whole lot of variations of this) (而且这个有很多变化)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.