Python中的自制阶乘函数

2024-04-25 19:24:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道一个代码可以工作,但我似乎不明白为什么这个代码只返回0。有人能帮我修一下吗?你知道吗

def factorial(x):
    hold = 1
    count = x
    if x == 0:
        return 1
    else:
        while count > 0:
            count -= 1
            hold *= count
            return hold

Tags: 代码returnifdefcountelsewhilehold
1条回答
网友
1楼 · 发布于 2024-04-25 19:24:05

它返回0,因为count将最终0在您的最后一个循环中。循环将对count = 1执行,并且您将用hold乘以0,因为您在相乘之前从count中减去1。乘法后必须减去1

def factorial(x):
    hold = 1
    count = x
    if x == 0:
        return 1
    else:
        while count > 0:
            hold *= count
            count -= 1  # moved this statement to the bottom
        return hold

但更好的功能是:

def factorial(x):
   hold = 1
   for number in xrange(2, x+1): # or range in python 3
       hold *= number
   return hold

相关问题 更多 >

    热门问题