c 实现1+1/2+1/3+....+n
时间: 2023-05-24 22:05:03 浏览: 72
#include <stdio.h>
int main()
{
int n;
float sum = 0.0;
printf("Enter a positive integer: ");
scanf("%d", &n);
for(int i=1; i<=n; i++)
{
sum += 1.0/i; // add the reciprocal of i to the sum
}
printf("The sum is: %.2f", sum); // print the sum with 2 decimal places
return 0;
}
相关问题
c语言求1+1/2+1/3+......+1/n
你可以使用一个循环来求解这个问题,循环从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/2+1/3+...+1/n
这个问题可以用循环语句来实现,以下是C语言代码:
#include <stdio.h>
int main() {
int n;
double sum = .;
printf("请输入n的值:");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
sum += 1. / i;
}
printf("1 + 1/2 + 1/3 + ... + 1/n = %lf", sum);
return ;
}
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)