分别用while语句、do-while语句、for语句编写程序,计算e≈1+1/1!+1/2!+...+1/n!
时间: 2023-11-18 16:05:12 浏览: 146
循环语句讲解
使用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);
```
阅读全文