计算正整数n1到n2的累加和(n1、n2的值由键盘输入)。
时间: 2024-06-14 12:04:42 浏览: 98
以下是两种计算正整数n1到n2的累加和的例子:
1. Java实现:
```java
import java.util.Scanner;
public class CalculateSum {
public static void main(String[] args) {
int n1, n2, sum = 0;
Scanner buf = new Scanner(System.in);
System.out.println("输入正整数n1: ");
n1 = buf.nextInt();
System.out.println("输入正整数n2: ");
n2 = buf.nextInt();
for (int i = n1; i <= n2; i++) {
sum += i;
}
System.out.println(n1 + "到" + n2 + "的累加和为:" + sum);
}
}
```
2. C语言实现:
```c
#include <stdio.h>
int calculateSum(int n1, int n2) {
int sum = 0;
for (int i = n1; i <= n2; i++) {
sum += i;
}
return sum;
}
int main() {
int n1, n2, sum;
printf("请输入n1的值:");
scanf("%d", &n1);
printf("请输入n2的值:");
scanf("%d", &n2);
sum = calculateSum(n1, n2);
printf("%d到%d的累加和为:%d\n", n1, n2, sum);
return 0;
}
```
阅读全文