c语言-分别用while语句、do-while语句、for语句编写程序,计算e = 1+1/1!+1/2!+...+1/n!
时间: 2024-04-27 21:15:27 浏览: 122
C语言程序设计-用do-while语句求1~100的累计和;.c
5星 · 资源好评率100%
以下是三种C语言计算e的程序,分别使用while语句、do-while语句、for语句实现:
1.使用while语句实现:
```c
#include <stdio.h>
int main() {
int n = 20, i = 1;
double sum = 1, a = 1;
while (i <= n {
a *= i;
sum += 1.0 / a;
i++;
}
printf("e = %lf\n", sum);
return 0;
}
```
2.使用do-while语句实现:
```c
#include <stdio.h>
int main() {
int n = 20, i = 1;
double sum = 1, a = 1;
do {
a *= i;
sum += 1.0 / a;
i++;
} while (i <= n);
printf("e = %lf\n", sum);
return 0;
}
```
3.使用for语句实现:
```c
#include <stdio.h>
int main() {
int n = 20;
double sum = 1, a = 1;
for (int i = 1; i <= n; i++) {
a *= i;
sum += 1.0 / a;
}
printf("e = %lf\n", sum);
return 0;
}
```
阅读全文