2015-02-04 63 views
2

我試圖編寫一個返回golden ratio到小數點後限制的程序。 我到目前爲止是這樣的:根據python中的變量限制小數點

def gr(n): 
    a, b = 0, 1 
    for x in range(0, n): 
     a, b = b, a+b 
    else: 
     return(a) 

    decimals = int(input("What amount of decimals do you want to see of the golden ratio?")) 
    ratio = gr(41)/gr(40) 
    print(format(ratio, '2f')) 

的問題是,我不能找到一種方法decimals格式化ratio的號碼。

+0

既然你沒有''break'在'for'循環中,我不太確定'else'是否需要在這裏。 – IanAuld

回答

0

傳遞精度/小數變量str.format:

decimals = int(input("What amount of decimals do you want to see of the golden ratio?")) 
ratio = gr(41)/gr(40) 
print("{:.{}f}".format(ratio,decimals)) 

例子:

In [3]: decimals = int(input("What amount of decimals do you want to see of the golden ratio?")) 
What amount of decimals do you want to see of the golden ratio?5 

In [4]: ratio = gr(41)/gr(40) 

In [5]: print("{:.{}f}".format(ratio,decimals)) 
1.61803 
-1

這裏是你正在嘗試做一個選擇:

print(round(ratio, 2)) 

上面的代碼將將值ratio四捨五入爲小數點後兩位。所以要做到小數整數,你可以這樣做:

print(round(ratio, decimals)) 
+0

與我發佈的內容有什麼不同? –

+0

嘗試使用兩者,然後你告訴我 –

+0

他沒有要求20的精度。他要求精確到'小數',我在我的答案中清楚地表明瞭這一點。 –