java输入n(n<13),计算1!+2!+3!+……+n!
时间: 2023-11-18 14:03:30 浏览: 90
java基础编程:求1+2!+3!+...的前n项的和
下面是Java代码实现输入n(n<13),计算1!+2!+3!+……+n!的值:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("输入n,打印1!+2!+3!+...+n!的值");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
while (n < 1 || n > 12) {//保证输入的数字大于0且小于13
System.out.println("请输入大于0且小于13的数字:");
n = in.nextInt();
}
int sum = 0;
for (int i = 1; i <= n; ++i)
sum += recursion(i);
System.out.println(sum);
}
//递归函数,求n!
public static int recursion(int n) {
if (n == 1)
return 1;
else
return n * recursion(n - 1);
}
}
```
阅读全文