温馨提示×

java中怎么求和

小亿
95
2024-09-26 02:57:05
栏目: 编程语言

在Java中,可以使用for循环、while循环或者数学库函数(如Math.sum())来求和。以下是几种不同的方法:

  1. 使用for循环:
public class Sum {
    public static void main(String[] args) {
        int n = 10;
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        System.out.println("1到" + n + "的和为:" + sum);
    }
}
  1. 使用while循环:
public class Sum {
    public static void main(String[] args) {
        int n = 10;
        int sum = 0;
        int i = 1;
        while (i <= n) {
            sum += i;
            i++;
        }
        System.out.println("1到" + n + "的和为:" + sum);
    }
}
  1. 使用Java 8的Stream API:
import java.util.stream.IntStream;

public class Sum {
    public static void main(String[] args) {
        int n = 10;
        int sum = IntStream.rangeClosed(1, n).sum();
        System.out.println("1到" + n + "的和为:" + sum);
    }
}
  1. 使用Math.sum()函数(仅适用于整数数组):
public class Sum {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        int sum = 0;
        for (int number : numbers) {
            sum += number;
        }
        System.out.println("数组元素的和为:" + sum);
    }
}

0