3种方式求阶乘
0. 利用while循环def factorial(x):
y=1
while x >= 1:
y = y * x
x -= 1
return y
correct = False
while not correct:
temp = input('请输入一个正整数:')
try:
result = factorial(int(temp))
correct = True
except Exception:
print('请输入一个正整数')
print(str(temp) + '的阶乘是:' + str(result) + '.')
1. 利用for循环
def factorial_1(n):
x = n
for i in range(1,n):
x *= i
return x
correct = False
while not correct:
temp = input('请输入一个正整数:')
try:
result = factorial_1(int(temp))
correct = True
except Exception:
print('请输入正整数')
print(str(temp) + '的阶乘是:' + str(result) + '.')
2. 利用递归
def factorial_2(n):
if n == 1:
return1
else:
return n * factorial_2(n - 1)
correct = False
while not correct:
temp = input('请输入一个正整数:')
try:
result = factorial_2(int(temp))
correct = True
except Exception:
print('请输入正整数!')
print(str(temp) + '的阶乘是:' + str(result) + '.') 条条道路通北京!
还可以使用函数求阶乘,使用指针求阶乘 再补充一个do-while循环,不写了
页:
[1]