编写一个程序,求s=1+(1+2)+(1+2+3)+…+(1+2+3+…+n)的 值。
时间: 2023-11-17 09:03:37 浏览: 56
【C语言】1+2+3+...+n的值
这里提供两种编程语言的解法:
C语言解法:
```c
#include <stdio.h>
int main() {
int n, i, j, sum = 0;
scanf("%d", &n);
for (i = 1; i <= n; i++) {
int temp = 0;
for (j = 1; j <= i; j++) {
temp += j;
}
sum += temp;
}
printf("%d", sum);
return 0;
}
```
Java语言解法:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int sum = 0;
for (int i = 1; i <= n; i++) {
int temp = 0;
for (int j = 1; j <= i; j++) {
temp += j;
}
sum += temp;
}
System.out.println(sum);
}
}
```
阅读全文