分别用while语句、do-while语句、for语句编写程序,计算e≈1+1/1!+1/2!+...+1/n!
时间: 2024-04-27 21:15:27 浏览: 124
以下是三种不同语句实现计算e≈1+1/1!+1/2!+...+1/n!的程序:
1. while语句实现:
```python
n = 20
sum = 0
i = 0
factorial = 1
while i <= n:
if i == 0:
factorial = 1
else:
factorial *= i
sum += 1 / factorial
i += 1
print("e ≈", sum)
```
2. do-while语句实现:
```python
n = 20
sum = 0
i = 0
factorial = 1
while True:
if i == 0:
factorial = 1
else:
factorial *= i
sum += 1 / factorial
i += 1
if i > n:
break
print("e ≈", sum)
```
3. for语句实现:
```python
n = 20
sum = 0
factorial = 1
for i in range(n+1):
if i == 0:
factorial = 1
else:
factorial *= i
sum += 1 / factorial
print("e ≈", sum)
```
相关问题
分别用while语句、do-while语句、for语句编写程序, 计算e≈1+1/1!+1/2!+...+1/n!
以下是三种不同的方法来计算e≈1+1/1!+1/2!+...+1/n!:
1. 使用while循环来计算
```python
n = int(input())
jie = 1
sum = 0
i = 1
while n >= i:
jie = jie * i
sum = sum + jie
i = i + 1
print(sum)
```
2. 使用do-while循环来计算
```java
public class Example1_3 {
public static void main(String args[]) {
double a = 1, b = 1, c = 0;
System.out.println("do-while循环:");
do {
c = b + c;
a++;
b = (1.0 / a) * b;
} while (a <= 20);
System.out.println(" " + c);
System.out.println("for循环:");
}
}
```
3. 使用for循环来计算
```java
public class Example1_3 {
public static void main(String args[]) {
double a, b, c;
System.out.println("for循环:");
for (c = 0, b = 1, a = 1; a <= 20; a++) {
b *= (1.0 / a);
c += b;
}
System.out.println(" " + c);
}
}
```
分别用while语句、do-while语句、for语句编写程序,计算e≈1+1/1!+1/2!+...+1/n!
使用while语句计算e≈1+1/1!+1/2!+...+1/n!的代码如下所示:
```java
int n = 20;
double sum = 1.0, number = 1.0;
int i = 1;
while (i <= n) {
number /= i;
sum += number;
i++;
}
System.out.println("使用while循环计算的e≈" + sum);
```
使用do-while语句计算e≈1+1/1!+1/2!+...+1/n!的代码如下所示:
```java
int n = 20;
double sum = 1.0, number = 1.0;
int i = 1;
do {
number /= i;
sum += number;
i++;
} while (i <= n);
System.out.println("使用do-while循环计算的e≈" + sum);
```
使用for语句计算e≈1+1/1!+1/2!+...+1/n!的代码如下所示:
```java
int n = 20;
double sum = 1.0, number = 1.0;
for (int i = 1; i <= n; i++) {
number /= i;
sum += number;
}
System.out.println("使用for循环计算的e≈" + sum);
```
阅读全文