問題描述
我有兩個(gè)整數(shù)值 a
和 b
,但我需要它們的浮點(diǎn)比率.我知道 a <b
并且我想計(jì)算 a/b
,所以如果我使用整數(shù)除法,我將始終得到 0,余數(shù)為 a
.
I have two integer values a
and b
, but I need their ratio in floating point. I know that a < b
and I want to calculate a / b
, so if I use integer division I'll always get 0 with a remainder of a
.
如何在下面的 Python 中強(qiáng)制 c
為浮點(diǎn)數(shù)?
How can I force c
to be a floating point number in Python in the following?
c = a / b
推薦答案
在 Python 2 中,兩個(gè)整數(shù)相除產(chǎn)生一個(gè)整數(shù).在 Python 3 中,它產(chǎn)生一個(gè)浮點(diǎn)數(shù).我們可以通過從 __future__
導(dǎo)入來(lái)獲得新的行為.
In Python 2, division of two ints produces an int. In Python 3, it produces a float. We can get the new behaviour by importing from __future__
.
>>> from __future__ import division
>>> a = 4
>>> b = 6
>>> c = a / b
>>> c
0.66666666666666663
這篇關(guān)于如何強(qiáng)制除法為浮點(diǎn)數(shù)?除法不斷四舍五入為0?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!