编写程序,求n!。 编写程序,求1!+3!+5!+7!+9!。使用Python
时间: 2023-12-01 18:42:39 浏览: 86
C语言编写1!+2!+3!+.....+n!.doc
以下是两种Python计算阶乘的方法:
1.使用for循环计算n!:
```python
n = int(input())
factorial = 1
if n < 0:
print("抱歉,负数没有阶乘")
elif n == 0:
print("0的阶乘为1")
else:
for i in range(1, n + 1):
factorial = factorial * i
print(n, "的阶乘为", factorial)
```
2.使用递归函数计算n!:
```python
def jie(n):
if n == 1:
return 1
else:
return n*jie(n-1)
n = int(input())
if n < 0:
print("抱歉,负数没有阶乘")
elif n == 0:
print("0的阶乘为1")
else:
print(n, "的阶乘为", jie(n))
```
以下是Python计算1!+3!+5!+7!+9!的程序:
```python
sum = 0
for i in range(1, 10, 2):
factorial = 1
for j in range(1, i + 1):
factorial = factorial * j
sum = sum + factorial
print("1!+3!+5!+7!+9!的和为", sum)
```
阅读全文