用递归求1!+2!+……+n!,从键盘输入n的值。
时间: 2023-12-02 14:02:04 浏览: 101
以下是Java和C语言两种递归求1!+2!+……+n!的例子,其中n从键盘输入:
1. Java代码:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入一个正整数n:");
int n = input.nextInt();
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += factorial(i);
}
System.out.println("1!+2!+...+n!的和为:" + sum);
}
public static int factorial(int n) {
if (n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
}
```
2. C语言代码:
```c
#include <stdio.h>
int factorial(int n);
int main() {
int n, sum = 0;
printf("请输入一个正整数n:");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
sum += factorial(i);
}
printf("1!+2!+...+n!的和为:%d\n", sum);
return 0;
}
int factorial(int n) {
if (n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
```
阅读全文