读入一个正整数x,输出1+2+3+…x的累加和用c语言编程
时间: 2023-12-17 09:04:07 浏览: 108
以下是对应的 C 语言代码:
```
#include <stdio.h>
int main() {
int x, sum = 0;
printf("请输入一个正整数x:");
scanf("%d", &x);
for (int i = 1; i <= x; i++) {
sum += i;
}
printf("1+2+3+...+%d=%d\n", x, sum);
return 0;
}
```
我们使用 `scanf` 函数读入一个正整数 `x`,然后使用 `for` 循环计算1到x的累加和,并将结果存储在 `sum` 变量中。最后使用 `printf` 函数输出计算结果。
相关问题
读入一个正整数x,输出1+2+3+…x的累加和c语言for循环
可以这样实现:
```c
#include <stdio.h>
int main() {
int x;
printf("输入一个正整数x:");
scanf("%d", &x);
int sum = 0;
for(int i = 1; i <= x; i++) {
sum += i;
}
printf("1到%d的累加和为%d\n", x, sum);
return 0;
}
```
c语言读入1 个正整数 n(n<=100),计算并输出1+1/2+1/3+……+1/n 。(保留两位小数)
以下是一个简单的 C 语言程序,可以实现该功能:
```c
#include <stdio.h>
int main() {
int n;
double sum = 0.0;
printf("请输入一个正整数n(n<=100):");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
sum += 1.0 / i;
}
printf("1 + 1/2 + ... + 1/%d = %.2f\n", n, sum);
return 0;
}
```
在该程序中,我们首先读入一个正整数 n,然后使用一个 for 循环来计算并累加 1/1,1/2,1/3,...,1/n 的和。最后,我们使用 printf 函数输出结果,保留两位小数。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)