用java计算1!+2!+...+10!。
时间: 2023-09-23 13:12:24 浏览: 46
可以使用循环和递归两种方式实现,以下是两种方法的代码示例:
1. 循环实现方式:
```java
public class Factorial {
public static void main(String[] args) {
int n = 10;
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
System.out.println("1! + 2! + ... + 10! = " + result);
}
}
```
2. 递归实现方式:
```java
public class Factorial {
public static void main(String[] args) {
int n = 10;
int result = 0;
for (int i = 1; i <= n; i++) {
result += factorial(i);
}
System.out.println("1! + 2! + ... + 10! = " + result);
}
public static int factorial(int n) {
if (n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
}
```
以上两种方式的输出结果都是:1! + 2! + ... + 10! = 4037913。