编写JavaApplication 程序,分别用do-while和for循环计算1+1/2!+1/3!+1/4!.的前20项和
时间: 2023-10-04 21:04:59 浏览: 88
好的,我理解了你的要求。以下是使用do-while和for循环计算1 1/2! 1/3! 1/4!.的前20项的Java代码:
使用do-while循环:
```
public class Factorial {
public static void main(String[] args) {
double sum = 1;
double factorial = 1;
int i = 1;
do {
factorial *= i;
sum += 1.0 / factorial;
i++;
} while (i <= 20);
System.out.println(sum);
}
}
```
使用for循环:
```
public class Factorial {
public static void main(String[] args) {
double sum = 1;
double factorial = 1;
for (int i = 1; i <= 20; i++) {
factorial *= i;
sum += 1.0 / factorial;
}
System.out.println(sum);
}
}
```
希望能够帮到你!
阅读全文