c语言求1+1/2+1/3+......+1/n
时间: 2023-08-23 21:05:53 浏览: 2097
你可以使用一个循环来求解这个问题,循环从1到n,每次将1/i加到一个累加器中,最后输出累加器的值即可。以下是c语言实现代码:
```c
#include <stdio.h>
int main() {
int n;
float sum = 0.0;
printf("请输入一个正整数n: ");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
sum += 1.0 / i;
}
printf("1 + 1/2 + 1/3 + ... + 1/n = %f\n", sum);
return 0;
}
```
需要注意的是,在计算1/i时,需要将i转换成浮点数,这样才能得到小数结果。
相关问题
c语言求1+1/3+1/5+..+1/n
以下是C语言求1+1/3+1/5+..+1/n的代码:
```c
#include <stdio.h>
int main() {
int n;
double sum = 0;
printf("请输入n的值:");
scanf("%d", &n);
for (int i = 1; i <= n; i += 2) {
sum += 1.0 / i;
}
printf("sum=%lf", sum);
return 0;
}
```
代码解释:
1. 首先定义变量n表示求和的最大值,sum表示求和的结果。
2. 通过scanf函数获取用户输入的n的值。
3. 使用for循环从1开始,每次加2,直到i大于n为止,这样就可以保证只加奇数项。
4. 在循环中,每次将1/i加到sum中。
5. 最后输出sum的值。
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)
![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)