c语言-分别用while语句、do-while语句、for语句编写程序,计算e = 1+1/1!+1/2!+...+1/n!
时间: 2024-04-27 16:15:27 浏览: 109
290-用do-while语句控制P0口8位LED流水点亮(51单片机C语言实例Proteus仿真和代码)
以下是三种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;
}
```
阅读全文