用Java分别用do+while和for循环计算1+1/2!+1/3!+1/4!+...的前20项之和 的代码
时间: 2024-01-30 07:02:25 浏览: 119
以下是Java分别使用do-while和for循环计算1+1/2!+1/3!+1/!+...的前20项之和的代码:
1. 使用do-while循环:
```java
public class Example1_3 {
public static void main(String args[]) {
double a = 1, b = 1, c = 0;
System.out.println("do-while循环:");
do {
c = b + c;
a++;
b = (1.0 / a) * b;
} while (a <= 20);
System.out.println(" " + c);
}
}
```
2. 使用for循环:
```java
public class Example1_3 {
public static void main(String args[]) {
double a, b, c;
System.out.println("for循环:");
for (c = 0, b = 1, a = 1; a <= 20; a++) {
b *= (1.0 / a);
c += b;
}
System.out.println(" " + c);
}
}
```
阅读全文