编程实现计算1+1/2!+1/3!+......+1/n!的值。要求n由用户从键盘输入。java
时间: 2023-11-12 17:05:27 浏览: 104
可以使用循环和递归两种方式实现计算1+1/2!+1/3!+......+1/n!的值。
循环实现方式如下:
```
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入n的值:");
int n = scanner.nextInt();
double sum = 0;
double factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
sum += 1 / factorial;
}
System.out.println("1+1/2!+1/3!+......+1/n!的值为:" + sum);
}
}
```
递归实现方式如下:
```
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入n的值:");
int n = scanner.nextInt();
double sum = 0;
for (int i = 1; i <= n; i++) {
sum += getFactorial(i);
}
System.out.println("1+1/2!+1/3!+......+1/n!的值为:" + sum);
}
public static double getFactorial(int n) {
if (n == 1) {
return 1;
} else {
return 1.0 / n / getFactorial(n - 1);
}
}
}
```
阅读全文