How can I force division to be floating point? Division keeps rounding down to 0?(如何强制除法为浮点数?除法不断四舍五入为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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何强制除法为浮点数?除法不断四舍五入为0?
基础教程推荐
- 包装空间模型 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
