0

重複の可能性:
Python で除算を強制的に浮動小数点にするにはどうすればよいですか?

この質問がすでに出されていたら、大変申し訳ありません。

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 と入力すると、目的の結果が得られることはわかっていますが、それを行う別の方法はありますか?

4

3 に答える 3

2

あなたが持っている他のオプションは(私はそれをお勧めしませんが)使用することです

from __future__ import division

その後

>>> 7 / 9
0.7777777777777778

これはPEP 238に基づいています。

于 2012-12-10T02:00:33.377 に答える
1

それらの1つを次のようにしfloatます。

float(timothy_lewis_three_pointers_made) / timothy_lewis_three_pointers_attempted
于 2012-12-10T01:57:04.520 に答える
1

整数除算を行っています。それらの少なくとも 1 つを float 値にする

percentage = float(_made) / float(_attempted)

新しい文字列フォーマット メソッドを使用して、パーセンテージの見栄えの良い出力を取得することもできます。

"Three point percentage: {:.2%}".format(7.0/9)
# OUT: ' Three point percentage: 77.78%'
于 2012-12-10T02:03:11.190 に答える