c语言用do-while循环计算S=1+1/1!+1/2!+1/3!+…+1/n!
时间: 2023-11-27 19:02:25 浏览: 38
以下是C语言使用do-while循环计算S=1+1/1!+1/2!+1/3!+…+1/n!的代码实现:
```c
#include <stdio.h>
int main() {
int n, i = 1;
double a = 1, sum = 1;
printf("请输入n的值:");
scanf("%d", &n);
do {
a *= i;
sum += 1.0 / a;
i++;
} while (i <= n);
printf("S的值为:%lf", sum);
return 0;
}
```
相关问题
用C语言编写的使用do-while循环计算S=1+1/1!+1/2!+1/3!+...+1/n!的程序:
下面是使用C语言编写的使用do-while循环计算S=1+1/1!+1/2!+1/3!+...+1/n!的程序:
```c
#include <stdio.h>
int main() {
int n, i = 1;
double s = 1, t = 1;
printf("请输入n的值:");
scanf("%d", &n);
do {
t *= i;
s += 1 / t;
i++;
} while (i <= n);
printf("S的值为:%lf\n", s);
return 0;
}
```
该程序使用了一个do-while循环,先计算出每个阶乘的值,再将每个阶乘的倒数加到S中,最后输出S的值。
在C语言中用do-while语句计算e≈1+1/1!+1/2!+…+1/n!
以下是在C语言中使用do-while语句计算e≈1+1/1!+1/2!+…+1/n!的代码:
```c
#include <stdio.h>
int main() {
int n, i = 1;
double s = 1, f = 1;
printf("请输入一个正整数(赋给n):");
scanf("%d", &n);
do {
f *= i; // 计算i的阶乘
s += 1.0 / f; // 计算每一项的值并加到s中
i++; // i加1
} while (i <= n);
printf("e ≈ %f\n", s); // 输出结果
return 0;
}
```
该程序中,我们使用了do-while语句来计算e的近似值。在循环中,我们定义了变量i表示当前项的下标,变量s表示e的近似值,变量f表示当前项的分母的阶乘。在每次循环中,我们先计算当前项的分母的阶乘,然后计算当前项的值,并将其加到s中。最后输出s的值即可。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.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)