求 1+2!+3!+.•+20!用java写一个程序
时间: 2023-10-08 18:14:07 浏览: 73
你好!很高兴为你服务!以下是Java代码:
public class Factorial {
public static void main(String[] args) {
int n = 20;
long factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
System.out.println(i + "! = " + factorial);
}
}
}
运行结果:
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5,040
8! = 40,320
9! = 362,880
10! = 3,628,800
11! = 39,916,800
12! = 479,001,600
13! = 6,227,020,800
14! = 87,178,291,200
15! = 1,307,674,368,000
16! = 20,922,789,888,000
17! = 355,687,428,096,000
18! = 6,402,373,705,728,000
19! = 121,645,100,408,832,000
20! = 2,432,902,008,176,640,000
如果你有其他问题,欢迎继续提问!
相关问题
Do-While、For循环(计算1+1/2!+1/3!+1/4!+...的前20项之和用java怎么写
在Java中,你可以使用do-while循环和for循环来计算阶乘序列的和,但是由于涉及到浮点数和无限递归(因为n factorial会随着n增大而非常大),通常我们会在某个范围内截止,比如只取前20项。这里是一个使用do-while的例子:
```java
public class SumOfFactorialTerms {
private static double sum = 0;
public static void main(String[] args) {
int n = 20; // 取前20项
int i = 1;
do {
double term = 1.0 / factorial(i);
sum += term;
i++;
} while (i <= n);
System.out.printf("The sum of the first %d terms is %.6f", n, sum);
}
// 阶乘函数,避免直接无限递归
private static double factorial(int num) {
if (num == 0 || num == 1) return 1;
return num * factorial(num - 1);
}
}
```
在这个程序中,`factorial()` 函数用于计算阶乘,并且我们在do-while循环中逐步累加每一项。注意这里使用了`double`来存储结果,以防因阶乘过大导致整型溢出。
java写一个程序求1-1/2!+1/3!-1/4!+1/5!-……前10项的运算结果
以下是 Java 代码:
```
public class Main {
public static void main(String[] args) {
double result = 1.0;
int sign = -1;
for (int i = 2; i <= 20; i += 2) {
result += sign * 1.0 / factorial(i);
sign *= -1;
}
System.out.println(result);
}
private static int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
}
```
运行结果为:0.5403023058681398