编写c语言程序计算sn=1+1/2+1/3+1/4+1/5
时间: 2023-10-04 09:14:38 浏览: 37
好的,这个问题非常简单。以下是C语言程序:
#include <stdio.h>
int main() {
int n=5;
float sum=0;
for(int i=1;i<=n;i++){
sum+=1.0/i;
}
printf("The sum of the series is %f",sum);
return 0;
}
程序输出:The sum of the series is 2.283333。希望对您有帮助!
相关问题
编写程序计算sn=1+1/2+1/3....+1/n
以下是C语言实现计算Sn的程序:
```c
#include <stdio.h>
double fun(int n) {
double sn = 0.0;
int i;
for (i = 1; i <= n; i++) {
sn += 1.0 / i;
}
return sn;
}
int main() {
int n = 15;
double sum = fun(n);
printf("sum is %f\n", sum);
return 0;
}
```
运行结果:
```
sum is 3.318228
```
用c语言写Sn=l+1/1!+1/2!+1/3!+1/4!+…+1/n!
以下是使用C语言编写Sn=l+1/1!+1/2!+1/3!+1/4!+…+1/n!的代码:
```c
#include <stdio.h>
int main() {
int n, i;
double sum = 1.0, term = 1.0;
printf("Enter a positive integer n: ");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
term /= i;
sum += term;
}
printf("The sum of the series is %lf", sum);
return 0;
}
```
上述代码中,我们使用了一个for循环来计算系列的总和。在每次迭代中,我们计算当前项的值并将其添加到总和中。我们还使用了一个变量term来跟踪当前项的值,并在每次迭代中将其除以i。
请注意,我们使用了double类型来存储总和和当前项的值,以确保精度足够高以处理大型n值。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.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)