计算正整数n1到n2的累加和(n1、n2的值由键盘输入)
时间: 2024-06-14 09:04:39 浏览: 87
计算1加到n的和
5星 · 资源好评率100%
以下是计算正整数n1到n2的累加和的Java代码示例:
```java
import java.util.Scanner;
public class CalculateSum {
public static void main(String[] args) {
int n1, n2, sum = 0;
Scanner scanner = new Scanner(System.in);
System.out.print("输入第一个正整数n1: ");
n1 = scanner.nextInt();
System.out.print("输入第二个正整数n2: ");
n2 = scanner.nextInt();
for (int i = n1; i <= n2; i++) {
sum += i;
}
System.out.println("n1到n2的累加和为: " + sum);
}
}
```
阅读全文