编写函数求n!,主函数通过调用函数实现sum=1!+2!+…n!(n由键盘输入)
时间: 2023-10-06 16:09:33 浏览: 74
以下是Python实现:
```python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n = int(input("请输入n的值:"))
sum = 0
for i in range(1, n+1):
sum += factorial(i)
print("1! + 2! + ... + n! =", sum)
```
以下是Java实现:
```java
import java.util.Scanner;
public class Main {
public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n-1);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入n的值:");
int n = scanner.nextInt();
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += factorial(i);
}
System.out.println("1! + 2! + ... + n! = " + sum);
}
}
```
阅读全文