2013-04-08 65 views
0

我不是一個非常有經驗的程序員,但我只是寫了這個在Python中試圖找到e,使用定義e是1/0的總和! + 1/1! + 1/2! etc ...因子不輸出一個整數

我遇到的問題是def factorial不輸出整數。我意識到它不會給出它的寫法,但我不知道我該如何做到。 total是我想從def factorial作爲int輸出。

e = 0 

def factorial(m): 
    n = m - 1 
    total = 1 
    if n > 0: 
     total = m 
    while n > 0: 
     total = total * n 
     n = n - 1 

for w in range(0,100): 
    s = factorial(w) 
    e = e + (1/s) 

print(e) 
+8

得到喜歡這個標題... – Bitwise 2013-04-08 01:43:27

+0

使用return,lol @Bitwise – xxmbabanexx 2013-04-08 01:46:20

+1

'e'是一個實數。無論如何,你總不希望總數是一個整數。整數僅表示自然數(包括負數)。 – 2013-04-08 01:46:48

回答

6
def factorial(m): 
    n = m - 1 
    total = 1 
    if n > 0: 
     total = m 
    while n > 0: 
     total = total * n 
     n = n - 1 
    return total 

編輯:問題是,爲了從factorial獲取信息,你必須使用一個return語句。評估return之後的任何內容,並將其用作s = factorial(w)中的s的值。

+0

如果你解釋了問題所在(即使這對你和我來說可能很明顯),情況會更好。 – 2013-04-08 01:45:46

+0

Lo siento。添加了一個解釋。 – hatkirby 2013-04-08 01:47:19

2

Feffernoose的代碼工作。但爲了提高性能,您最好使用「yield」語句來構建一個可迭代對象。

e = 0 
def factorial(m): 
    assert(m>1) 
    current = 0 
    total = 1 
    while current<=m: 
     yield total 
     current += 1 
     total *= current 

for w in factorial(100): 
    e = e + (1/w) 
print(e) 

更新:在「return」的解決方案中,約需要O(n * n)時間來進行階乘值計算。但是對於「收益率」,你只需要O(n)。