如何对0到1000之间的所有整数求和

时间:2018-11-07 18:24:07

标签: java loops class

如何将所有整数加起来为1000

package proba;

public class Proba {

    public static void main(String[] args) {
        int a = 1;
        int whole = 0;

        int n = 1000;
        int m = 500;
        while (a <= n) {
            if (a % 2 == 0) {
                whole += ;

            }
            a++;
            System.out.println("Rezultat parnih je: " + whole);
        }
    }

}

2 个答案:

答案 0 :(得分:1)

对于0到1000之间的所有数字,for loop

int sum = 0;
for (int i = 0; i < 1000; i++) {
    sum += i;
}
System.out.println(sum);

对于所有偶数,请使用if来查看它们是否是偶数

if (i % 2 == 0) // remainder is 0, meaning even
    sum += i;

编辑:添加偶数并减去奇数

int sumOfEven;
for (int i = 0; i < 1000; i++) {
    if (i % 2 == 0) {
        sumOfEven += i;
    }
}

int sumOfOdd;
for (int i = 0; i < 500; i++) {
    if (i % 2 != 0) {
        sumOfOdd += i;
    }
}
System.out.println(sumOfEven - sumOfOdd); // Math.absolute can also be done here for a non-negative value

答案 1 :(得分:0)

仅将所有数字相加后再减去250效率不高。只需在总和中过滤掉不需要的

int sum = IntStream.rangeClosed(1, 1000)
                   .filter(i -> i >= 500 || i % 2 == 0)
                   .sum();
System.out.println(sum);