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