1+1/2+....+1/n的c语言
时间: 2023-11-06 21:08:22 浏览: 72
求1+1/2+....+1/n的C语言代码可以参考以下代码:
```
#include <stdio.h>
int main() {
int n;
double sum = 0.0;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
sum += 1.0 / i;
}
printf("sum=%.4lf", sum);
return 0;
}
```
其中,变量n表示求和的项数,sum表示求和的结果。通过for循环遍历每一项,将每一项的倒数加到sum中即可。需要注意的是,为了避免整数除法的问题,需要将1.0转换为浮点数。最后输出结果时,使用%.4lf格式化输出,保留4位小数。
相关问题
C语言2/1+3/2+4/3+...+(n+1)/n
以下是两种C语言求和的例子:
1. 使用for循环求和
```c
#include<stdio.h>
int main () {
int n, i;
scanf("%d", &n);
float sum = 0.0;
for(i=1; i<=n; i++){
sum += (i+1)/(float)i;
}
printf("f(%d)=%.3f", n, sum);
return 0;
}
```
2. 使用while循环求和
```c
#include<stdio.h>
int main() {
int n;
float sum = 0;
printf("请输入一个通项n:\n");
scanf("%d", &n);
int j = 1;
while (j <= n) {
sum = sum + (j+1)/(float)j;
j++;
}
printf("前%d项的和为%.3f", n, sum);
return 0;
}
```
C语言求1+1/2+1/3+....+1/n之和
以下是C语言求1+1/2+1/3+....+1/n之和的程序:
```c
#include <stdio.h>
int main() {
int n;
float sum = 0;
printf("请输入一个通项n:\n");
scanf("%d", &n); // 读取用户输入
for (int j = 1; j <= n; j++) {
sum = sum + 1.0 / j;
}
printf("前%d项的和为%.3f", n, sum);
return 0;
}
```
用户需要输入一个整数n,程序会计算1+1/2+1/3+....+1/n的和,并输出结果。其中,sum变量用于存储和的值,j变量用于循环计算每一项的值。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.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)