、分别用+while+语句、do-while+语句、for+语句编写程序,计算+e≈1+1/1!+1/2!+...+1/n!
时间: 2023-11-20 22:06:19 浏览: 118
Lizi3_7.rar_4 3 2 1
以下是三种不同的语句实现计算e的程序:
1. while语句实现
```java
int n = 1;
double sum = 1, item = 1;
while (true) {
item = item / n;
sum += item;
n++;
if (item < 1e-6) {
break;
}
}
System.out.println("使用while循环计算的e=" + sum);
```
2. do-while语句实现
```java
int n = 1;
double sum = 1, item = 1;
do {
item = item / n;
sum += item;
n++;
} while (item >= 1e-6);
System.out.println("使用do-while循环计算的e=" + sum);
```
3. for语句实现
```java
int n = 1;
double sum = 1, item = 1;
for (int i = 1; item >= 1e-6; i++) {
item = item / i; sum += item;
n = i;
}
System.out.println("使用for循环计算的e=" + sum);
```
阅读全文