用while循环求编写求s=1+(1+2)+(1+2+3)+(1+2+3+...+n)的值
时间: 2023-05-31 17:02:48 浏览: 104
n = int(input("请输入n的值:"))
s = 0
i = 1
while i <= n:
j = 1
temp = 0
while j <= i:
temp += j
j += 1
s += temp
i += 1
print("s的值为:", s)
相关问题
编写程序计算s=1+2+3+…+n的值。
这道题目可以使用循环语句来实现。下面是三种不同的循环语句实现方式:
1.使用while循环语句实现:
```
#include <stdio.h>
int main() {
int n, i = 1, s = 0;
printf("请输入n的值:");
scanf("%d", &n);
while (i <= n) {
s += i;
i++;
}
printf("s=%d", s);
return 0;
}
```
2.使用for循环语句实现:
```
#include <stdio.h>
int main() {
int n, i, s = 0;
printf("请输入n的值:");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
s += i;
}
printf("s=%d", s);
return 0;
}
```
3.使用do-while循环语句实现:
```
#include <stdio.h>
int main() {
int n, i = 1, s = 0;
printf("请输入n的值:");
scanf("%d", &n);
do {
s += i;
i++;
} while (i <= n);
printf("s=%d", s);
return 0;
}
```
(2) 分别用 while 语句和 for 语句编写程序,求 S=1+2+3+……+100 的值
以下是两种方法来求1到100的和S:
1. 使用while循环语句
```c
#include <stdio.h>
int main() {
int i = 1, sum = 0;
while (i <= 100) {
sum += i;
i++;
}
printf("S=%d\n", sum);
return 0;
}
```
输出:S=5050
2. 使用for循环语句
```c
#include <stdio.h>
int main() {
int i, sum = 0;
for (i = 1; i <= 100; i++) {
sum += i;
}
printf("S=%d\n", sum);
return 0;
}
```
输出:S=5050
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)