利用函数的递归调用,求 s = 1!+2!+3!+4!+5!+...+n!。其中n在主函数用input赋值。返回最后的计算结果s,并在命令行用print函数输出“s = 1!+2!+3!+4!+5!+...+n!= ”
时间: 2023-11-25 09:04:45 浏览: 82
以下是利用函数递归调用求解 s = 1!+2!+3!+4!+5!+...+n! 的代码:
```python
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
n = int(input("请输入n的值:"))
s = 0
for i in range(1, n+1):
s += factorial(i)
print("s = 1!+2!+3!+4!+5!+...+n! = ", s)
```
相关问题
Python利用函数的递归调用,求 s = 1!+2!+3!+4!+5!+...+n!。其中n在主函数用input赋值。返回最后的计算结果s,并在命令行用print函数输出“s = 1!+2!+3!+4!+5!+...+n!= ”
以下是Python利用函数的递归调用,求 s = 1!+2!+3!+4!+5!+...+n!的代码实现:
```python
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
n = int(input("请输入n的值:"))
s = 0
for i in range(1, n+1):
s += factorial(i)
print("s = 1!+2!+3!+4!+5!+...+n! = ", s)
```
(3)利用函数的递归调用,求 s = 1!+2!+3!+4!+5!+...+n!。其中n在主函数用input赋值。返回最后的计算结果s,并在命令行用print函数输出“s = 1!+2!+3!+4!+5!+...+n!= ”。
以下是利用函数递归调用,求 s = 1!+2!+3!+4!+5!+...+n!的Python代码:
```python
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
n = int(input("请输入n的值:"))
s = 0
for i in range(1, n+1):
s += factorial(i)
print("s = 1!+2!+3!+4!+5!+...+n! = ", s)
```
阅读全文