2012-12-10 86 views
0

可能重複:
how can I force division to be floating point in Python?在Python中的分工。 7/9 = 0?如何阻止此?

我很抱歉,如果這個問題已經被問了。

timothy_lewis_three_pointers_attempted = 4 
timothy_lewis_three_pointers_made = 2 

print 'three pointers attempted: ' + str(timothy_lewis_three_pointers_attempted) 
print 'three pointers made: ' + str(timothy_lewis_three_pointers_made) 
print 'three point percentage: ' + str(timothy_lewis_three_point_percentage) 

我得到0的百分比。我怎麼才能說出.5?我知道,如果我將數字輸入爲4.0和2.0,我會得到期望的結果,但還有另一種方法嗎?

+0

順便說一句,你可以寫'打印「造個三分球:」,timothy_lewis_three_pointers_made'做同樣的事情 - 這是怎麼了'print'通常用於 –

回答

1

使他們的一個float

float(timothy_lewis_three_pointers_made)/timothy_lewis_three_pointers_attempted 
+0

非常感謝您! – dylan

2

你(雖然我不建議這樣做),另一種選擇是使用

from __future__ import division 

然後

>>> 7/9 
0.7777777777777778 

這是基於PEP 238

1

你在做整數除法。使其中至少有一個浮點值

percentage = float(_made)/float(_attempted) 

您還可以通過使用新的字符串格式方法獲得更好看的百分比輸出。

"Three point percentage: {:.2%}".format(7.0/9) 
# OUT: ' Three point percentage: 77.78%'