java分别用while循环和for循环计算1+1/2!+1/3!+1/4!+……的前20项和
时间: 2023-09-07 10:13:36 浏览: 183
使用while循环计算1+1/2!+1/3!+1/4!+……的前20项和的Java代码如下:
```java
public class Main {
public static void main(String[] args) {
int n = 1;
double sum = 0, factorial = 1;
while (n <= 20) {
factorial *= n;
sum += 1 / factorial;
n++;
}
System.out.println("前20项和为:" + sum);
}
}
```
使用for循环计算1+1/2!+1/3!+1/4!+……的前20项和的Java代码如下:
```java
public class Main {
public static void main(String[] args) {
double sum = 0, factorial = 1;
for (int n = 1; n <= 20; n++) {
factorial *= n;
sum += 1 / factorial;
}
System.out.println("前20项和为:" + sum);
}
}
```
这两段代码的输出结果都为:前20项和为:1.7182818284590455
阅读全文