晚上,
我是python的入门学生,遇到了一些麻烦。我正在尝试制作一个python factorial程序。它应该提示用户输入n,然后计算n的阶乘,除非用户输入-1。我被卡住了,教授建议我们使用while循环。我知道我甚至还没说到“if-1”这个问题。我不知道如何让python在不使用math.factorial函数的情况下计算阶乘。
import math
num = 1
n = int(input("Enter n: "))
while n >= 1:
num *= n
print(num)发布于 2013-10-01 12:05:03
学校里的“经典”阶乘函数是一个递归定义:
def fact(n):
rtr=1 if n<=1 else n*fact(n-1)
return rtr
n = int(input("Enter n: "))
print fact(n)如果你只是想要一种方法来解决你的问题:
num = 1
n = int(input("Enter n: "))
while n > 1:
num *= n
n-=1 # need to reduce the value of 'n' or the loop will not exit
print num如果您希望对小于1的数字进行测试:
num = 1
n = int(input("Enter n: "))
n=1 if n<1 else n # n will be 1 or more...
while n >= 1:
num *= n
n-=1 # need to reduce the value of 'n' or the loop will not exit
print num或者,在输入后测试n:
num = 1
while True:
n = int(input("Enter n: "))
if n>0: break
while n >= 1:
num *= n
n-=1 # need to reduce the value of 'n' or the loop will not exit
print num下面是一个使用reduce的函数方法
>>> n=10
>>> reduce(lambda x,y: x*y, range(1,n+1))
3628800发布于 2013-10-01 12:07:42
你们真的很接近。只需在每次迭代中更新n的值:
num = 1
n = int(input("Enter n: "))
while n >= 1:
num *= n
# Update n
n -= 1
print(num)发布于 2018-05-17 03:14:22
我是python的新手,这是我的factorial程序。
定义阶乘(N):
x = []
for i in range(n):
x.append(n)
n = n-1
print(x)
y = len(x)
j = 0
m = 1
while j != y:
m = m *(x[j])
j = j+1
print(m)阶乘(5)
https://stackoverflow.com/questions/19107715
复制相似问题