分别用while语句、do-while语句、for语句编写程序,计算e≈1+1/1!+1/2!+...+1/n!
时间: 2023-11-18 20:05:12 浏览: 155
C语言实现求1+2+3+……+100的和,要求分别用while、do while、for循环实现。.txt
使用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);
```
阅读全文