如何强制除法为浮点数?除法不断向下舍入到 0?

编程入门 行业动态 更新时间:2024-10-24 02:33:18
本文介绍了如何强制除法为浮点数?除法不断向下舍入到 0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个整数值 a 和 b,但我需要它们的浮点比.我知道 a <b 并且我想计算 a/b,所以如果我使用整数除法,我总是会得到 0 和 a 的余数.

如何强制 c 在下面的 Python 中成为浮点数?

c = a/b

解决方案

在 Python 2 中,两个整数相除产生一个整数.在 Python 3 中,它产生一个浮点数.我们可以通过从 __future__ 导入来获得新的行为.

>>>来自 __future__ 进口部门>>>一 = 4>>>乙 = 6>>>c = a/b>>>C0.666666666666666663

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.

How can I force c to be a floating point number in Python in the following?

c = a / b

解决方案

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?

本文发布于:2023-11-29 21:57:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647740.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:除法   浮点数   舍入到

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!