2016-07-29 84 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