英文:
For Loop - print operand divided by two
问题
for (int i = 80; i >= 5; i /= 2) {
System.out.println(i);
}
英文:
I've been given a for loop statement which I must replace the '???' so that the code prints 80,40,20,10,5.
for (??? ; ??? ; ??? ) {
System.out.println(i);
}
I've tried
for (int i = 80 ; i>=5 ; i/2) {
System.out.println(i);
}
But that obviously doesn't work, I'm not sure how to proceed. I can't add any additional statements, I must only use the for loop.
答案1
得分: 3
根据您的数据和问题,应该这样做。这里使用了三元运算符 ?:
,值得了解一下。
for (int i = 80; i >= 5; i /= 2) {
System.out.print(i > 5 ? i + "," : i + "\n");
}
英文:
Here is how it should be done based on your data and question. This makes use of the ternary operator ?:
which is worth knowing about.
for (int i = 80; i >= 5; i/=2) {
System.out.print(i > 5 ? i + "," : i +"\n" );
}
</details>
# 答案2
**得分**: 0
将`i/2`赋值给`i`,以便在每次迭代中更改`i`的值。
请按以下方式进行操作:
```java
for (int i = 80; i >= 5; i = i / 2) {
if (i > 5) {
System.out.print(i + ",");
} else {
System.out.print(i);
}
}
英文:
Assign i/2
to i
so that the value of i
can change in each iteration.
Do it as follows:
for (int i = 80 ; i>=5 ; i = i/2) {
if (i > 5) {
System.out.print(i + ",");
} else {
System.out.print(i);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论