在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);
}
}