如何强制除法为浮点数?除数一直舍入为0? [英] How can I force division to be floating point? Division keeps rounding down to 0?

查看:118
本文介绍了如何强制除法为浮点数?除数一直舍入为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.

如何强制 c 为浮点数

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆