循环 – 打印操作数除以二

huangapple go评论75阅读模式
英文:

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&gt;=5 ; i = i/2) { 
    if (i &gt; 5) {
        System.out.print(i + &quot;,&quot;); 
    } else {
        System.out.print(i); 
    }
}

huangapple
  • 本文由 发表于 2020年4月6日 23:50:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/61063720.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定