在Java中,可以使用for循环、while循环或者数学库函数(如Math.sum())来求和。以下是几种不同的方法:
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);
}
}
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);
}
}
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);
}
}
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);
}
}