分别用while语句、do-while语句、for语句编写程序,计算e=1+1/1!+1/2!+...+1/n
时间: 2024-04-27 08:15:32 浏览: 115
以下是三种不同语句实现计算e的程序:
1. while语句实现:
```python
n = 20
e = 1
i = 1
factorial = 1
while i <= n:
factorial *= i
e += 1 / factorial
i += 1
print("e =", e)
```
2. do-while语句实现:
```python
n = 20
e = 1
i = 1
factorial = 1
while True:
factorial *= i
e += 1 / factorial
i += 1
if i > n:
break
print("e =", e)
```
3. for语句实现:
```python
n = 20
e = 1
factorial = 1
for i in range(1, n+1):
factorial *= i
e += 1 / factorial
print("e =", e)
```
相关问题
c语言-分别用while语句、do-while语句、for语句编写程序,计算e = 1+1/1!+1/2!+...+1/n!
以下是三种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;
}
```
c语言-分别用while语句、do-while语句、for语句编写程序,计算m=1+1/1!+1/2!+...+1/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;
}
```
阅读全文