c语言-分别用while语句、do-while语句、for语句编写程序,计算e≈1+1/1!+1/2!+...+1/n!
时间: 2024-04-27 19:15:27 浏览: 115
以下是三种C语言计算e的程序,分别使用while语句、do-while语句、for语句实现:
1.使用while语句实现:
```c
#include <stdio.h>
int main() {
int n = 1;
double sum = 1, a = 1;
while (n <= 20) {
a *= n;
sum += 1.0 / a;
n++;
}
printf("e = %lf\n", sum);
return 0;
}
```
2.使用do-while语句实现:
```c
#include <stdio.h>
int main() {
int n = 1;
double sum = 1, a = 1;
do {
a *= n;
sum += 1.0 / a;
n++;
} while (n <= 20);
printf("e = %lf\n", sum);
return 0;
}
```
3.使用for语句实现:
```c
#include <stdio.h>
int main() {
int n;
double sum = 1, a = 1;
for (n = 1; n <= 20; n++) {
a *= n;
sum += 1.0 / a;
}
printf("e = %lf\n", sum);
return 0;
}
```
阅读全文