编写java程序,从键盘输入一个整数n,分别使用for循环和while循环语句计算 1+1/2!+1/3!+......+1/n!;
时间: 2024-09-08 11:04:44 浏览: 124
当你需要编写Java程序来计算阶乘和求和时,可以按照下面的步骤操作。首先,我们需要创建一个函数来计算阶乘,然后利用for和while循环来依次累加分数。
以下是使用for循环的例子:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个整数n:");
int n = scanner.nextInt();
double factorialSum = calculateFactorialSum(n);
System.out.printf("1 + 1/%d! + 1/(%d!) + ... + 1/%d! = %.2f", n, n, n, factorialSum);
}
// 计算阶乘的辅助函数
private static double calculateFactorial(int num) {
if (num == 0 || num == 1) return 1;
else return num * calculateFactorial(num - 1);
}
// 使用for循环计算1到1/n!的和
private static double calculateFactorialSum(int n) {
double sum = 1;
for (int i = 1; i <= n; i++) {
sum += 1 / factorial(i);
}
return sum;
}
// 阶乘的静态方法实现
private static double factorial(int num) {
return calculateFactorial(num);
}
}
```
接下来是使用while循环的版本:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个整数n:");
int n = scanner.nextInt();
double factorialSum = calculateFactorialSum(n);
System.out.printf("1 + 1/%d! + 1/(%d!) + ... + 1/%d! = %.2f", n, n, n, factorialSum);
}
// ...其他方法保持不变...
// 使用while循环计算1到1/n!的和
private static double calculateFactorialSum(int n) {
double sum = 1;
int i = 1;
while (i <= n) {
sum += 1 / factorial(i);
i++;
}
return sum;
}
}
```
阅读全文