分别For语岝、while语岝和do…while语岝用编写代码在主岟法中实岞岠罓1+1/2!+1/3!+…+1/20!
时间: 2024-10-08 09:09:40 浏览: 22
ASN.1与PKCS#7.pptx
首先,我们来看一下如何使用for、while和do...while这三个循环结构来计算这个序列:
1. **For循环**:
```java
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 20; i++) {
double factorial = calculateFactorial(i);
System.out.println(1 / factorial);
}
}
private static double calculateFactorial(int n) {
if (n == 0 || n == 1) return 1;
else return n * calculateFactorial(n - 1);
}
}
```
2. **While循环**:
```java
public class Main {
public static void main(String[] args) {
int i = 1;
while (i <= 20) {
double factorial = calculateFactorial(i);
System.out.println(1 / factorial);
i++;
}
}
private static double calculateFactorial(int n) {
if (n == 0 || n == 1) return 1;
else return n * calculateFactorial(n - 1);
}
}
```
3. **Do...While循环**:
```java
public class Main {
public static void main(String[] args) {
int i = 1;
do {
double factorial = calculateFactorial(i);
System.out.println(1 / factorial);
i++;
} while (i <= 20);
// 在do...while循环里,循环体至少会执行一次,所以在i++前添加对factorial的计算
}
private static double calculateFactorial(int n) {
if (n == 0 || n == 1) return 1;
else return n * calculateFactorial(n - 1);
}
}
```
以上三种循环都会计算从1到20的阶乘倒数之和。
阅读全文