2016-07-29 81 views
-6

不知道什么是错的,代码是给12,而不是24阶乘代码不工作

def factorial(x): 
    m=x-1 
    while m>0: 
     t=x*m 
     m-=1 
     return t 
    else: 
     return 1 
print factorial(4) 
+6

因为你正在返回while循环的第一次迭代。 –

+1

这不是唯一的问题,'t = x * m'没有意义。 – polku

回答

1

你的代码返回值和分配新的价值为t每次迭代

def factorial(x): 
...  t = 1 
...  while x>0: 
...   t *= x 
...   x-=1 
... 
...  return t 
print factorial(4) 
output: 
24 

----或----

from operator import mul 
def factorial(x): 
    return reduce(mul, range(1,x+1)) 
print factorial(4) 
output: 
24 
+0

尽管OP显然使用Python 2,但重要的是要注意,第二个示例在Python 3上不起作用,因为reduce不再位于std库中,必须从functools中导入。 – DeepSpace

+0

@DeepSpace感谢您指出。我将它写入我的笔记,当我切换到python 3.谢谢 – galaxyan

+0

我知道我的t值不断变化,所以代码只是返回给我的第一个值。但我不明白你的代码是什么 – Anonymous