package he; public class he { public static void main(String[] args){ int sum=0; int i=2; do{sum += i; i++; }while(i<=50&&i%2==0); System.out.println(sum); } } 求大神帮忙看看加了一个条件为啥就输出2了
while循环是满足条件然后循环,你那个 i=3 了,,所以i%2 ==0 是false 。跳出循环,sum就等于2
package com.demo06;
public class While {
public static void main(String[] args) {
int num=2;
int sum=0;
do{
sum=sum+num;
num=num+2;
}while((num<=50)&&(num%2==0));
System.out.println("50以内的偶数之和为:"+sum);
}
}
do-while循环是先执行一次,再判断while括号里条件是否满足,满足后才能继续循环,否则循环结束。本题的循环条件要满足i是偶数,但是i之前执行了i++后变为3了,不满足条件,所以跳出循环输出为2.
package he;
public class he {
public static void main(String[] args){
int sum=0;
int i=2;
do{sum += i;
i++;
}while(i<=50&&i%2==0);
System.out.println(sum);
}
}