Java 1 到 100 之间的偶数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19769551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Even numbers between 1 and 100 inclusive
提问by Ahmed Beco
I need to display all the even numbers between 1-100 inclusive using a while
loop. I couldn't mange it. I think it should be something like this :
我需要使用while
循环显示 1-100 之间的所有偶数。我无法控制它。我认为它应该是这样的:
int e = 1;
while (( 1 < e ) && ( e < 100 )) {
e = e + 1;
if (e % 2==0) {
System.out.print(" " + e);
}
}
Edit - I did it like this:
编辑 - 我是这样做的:
while ( e <= 100 ) {
e = e + 1;
if ( e % 2 == 0)
{
System.out.print(" " + e);
}
}
回答by Udo Klimaschewski
You only need to fix your while statement and move the adding:
您只需要修复您的 while 语句并移动添加:
while (e <= 100) {
if (e % 2 == 0)
System.out.println(e);
e = e + 1;
}
回答by Prabhakaran Ramaswamy
Use while ( e <= 100 )
instead of while (( 1 < e ) && ( e < 100 ))
.
使用while ( e <= 100 )
代替while (( 1 < e ) && ( e < 100 ))
。
回答by upog
try
尝试
while (( 1 <= e ) && ( e <= 100 ))
回答by SteeveDroz
Simple version:
简单版:
int e = 2;
while (e <= 100) {
System.out.print(" " + e);
e += 2;
}
回答by Pankaj Prakash
You can use any of the following
您可以使用以下任何一种
int i = 2;
while(i<=100)
{
printf("%d\n", i);
i+=2;
}
OR you may use
或者你可以使用
int i = 1;
while(i<=100)
{
if(i%2==0)
printf("%d\n", i);
i++;
}