分别用while语句、do-while语句、for语句编写程序, 计算e≈1+1/1!+1/2!+...+1/n!
时间: 2023-11-27 11:04:28 浏览: 76
用while循环语句来计算1+1/2+2/3+3/4+...+99/100之和
以下是三种不同的方法来计算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);
}
}
```
阅读全文