马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
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:
return 1
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) + '.')
|