如何强制除法为浮点数?除法不断四舍五入为0?
- 作者: Evo丶小寶
- 来源: 51数据库
- 2022-10-20
问题描述
我有两个整数值 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
推荐阅读
热点文章
Discord.py(重写)on_member_update 无法正常工作
0
Discord.py 在 vc 中获取用户分钟数
0
discord.py 重写 |为我的命令出错
0
Discord.py rewrite 如何 DM 命令?
0
播放音频时,最后一部分被切断.如何解决这个问题?(discord.py)
0
在消息删除消息 Discord.py
0
如何使 discord.py 机器人私人/直接消息不是作者的人?
0
(Discord.py) 如何获取整个嵌入内容?
0
Discord bot 尽管获得了许可,但不能提及所有人
0
Discord.py discord.NotFound 异常
0
