本文介紹了如何強制除法為浮點數?除法不斷四舍五入為0?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我有兩個整數值 a
和 b
,但我需要它們的浮點比率.我知道 a <b
并且我想計算 a/b
,所以如果我使用整數除法,我將始終得到 0,余數為 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 中強制 c
為浮點數?
How can I force c
to be a floating point number in Python in the following?
c = a / b
推薦答案
在 Python 2 中,兩個整數相除產生一個整數.在 Python 3 中,它產生一個浮點數.我們可以通過從 __future__
導入來獲得新的行為.
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
這篇關于如何強制除法為浮點數?除法不斷四舍五入為0?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!