java 编程求出1-100之间偶数的和

2024-11-26 03:24:29
推荐回答(2个)
回答1:

public class Test{

public static void main(String[] args){

int sum = 0;
for(int i = 1; i <= 100; i ++) {
if(i % 2 == 0) {
sum = sum + i;
}System.out.println(sum);
}

}
}

回答2:

int i =1,sum=0;
for(i=1; i<=100; i++) {
if(i%2 == 0) { //对2求模,偶数才是0
sum += i;
}
}