c语言-分别用while语句、do-while语句、for语句编写程序,计算m=1+1/1!+1/2!+...+1/n!
时间: 2024-04-27 11:15:27 浏览: 114
c代码-12、/*用do...while语句计算1到n的累乘之积,即计算n!*/
以下是三种C语言计算m的方法:
1. while循环实现
```c
#include <stdio.h>
int main()
{
double sum = 0, a = 1;
int i = 1, n = 20;
while(i <= n)
{
a *= i;
sum += 1.0 / a;
i++;
}
printf("%lf", sum);
return 0;
}
```
2. do-while循环实现
```c
#include <stdio.h>
int main()
{
double sum = 0, a = 1;
int i = 1, n = 20;
do
{
a *= i;
sum += 1.0 / a;
i++;
}while(i <= n);
printf("%lf", sum);
return 0;
}
```
3. for循环实现
```c
#include <stdio.h>
int main()
{
double sum = 0, a = 1;
int i, n = 20;
for(i = 1; i <= n; i++)
{
a *= i;
sum += 1.0 / a;
}
printf("%lf", sum);
return 0;
}
```
阅读全文