用do-while和for循环计算1+1/2!+···+1/20!的和
时间: 2023-05-28 14:03:23 浏览: 94
使用do-while循环:
int i = 1;
double sum = 0;
double factorial = 1;
do {
factorial *= i;
sum += 1 / factorial;
i++;
} while (i <= 20);
使用for循环:
double sum = 0;
double factorial = 1;
for (int i = 1; i <= 20; i++) {
factorial *= i;
sum += 1 / factorial;
}
相关问题
java分别用do-while和for循环计算1+1/2!+1/3!+1/4! +…+1/20!
以下是Java分别使用do-while和for循环计算1+1/2!+1/3!+1/4! +…+1/20!的代码实现:
1.使用for循环实现:
```java
public class Test {
public static void main(String args[]){
double sum=0;
int a = 1;
for(int i = 1; i <= 20;i++){
a *= i;
sum += 1.0/a;
}
System.out.println(sum);
}
}
```
2.使用do-while循环实现:
```java
public class Test {
public static void main(String args[]){
double sum=0;
int a = 1, i = 1;
do{
a *= i;
sum += 1.0/a;
i++;
}while(i <= 20);
System.out.println(sum);
}
}
```
java分别用do-while和for循环计算1+1/2!+1/3!+...的前20项和
在Java中,你可以使用do-while和for循环结合递归的方式来计算1+1/2! + 1/3! + ...的前20项和。这里是一个示例代码:
```java
public class Main {
public static void main(String[] args) {
double sum = 1.0;
int n = 20; // 前20项
// 使用do-while循环
int index = 1;
do {
double factorialTerm = calculateFactorial(index);
sum += 1.0 / factorialTerm;
index++;
} while (index <= n);
System.out.printf("前 %d 项和: %.2f\n", n, sum);
// 使用for循环
for (int i = 1; i <= n; i++) {
double factorialTerm = calculateFactorial(i);
sum += 1.0 / factorialTerm;
}
System.out.printf("前 %d 项和(使用for): %.2f\n", n, sum);
}
// 计算阶乘
private static double calculateFactorial(int num) {
if (num == 0 || num == 1)
return 1;
else
return num * calculateFactorial(num - 1);
}
}
```
在这个例子中,`calculateFactorial()`函数用于计算阶乘,然后在do-while和for循环中逐步累加到总和`sum`上。
阅读全文