为什么这个除法在 Python 中不起作用? [英] Why doesn't this division work in Python?

查看:49
本文介绍了为什么这个除法在 Python 中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑:

<预><代码>>>>分子 = 29>>>分值 = 1009>>>打印 str(float(numerator/denom))0.0

如何让它返回小数?

解决方案

在版本 3 之前,Python 的除法运算符/在提供两个整数参数时表现得类似于 C 的除法运算符:它返回一个整数结果,当有小数部分时会被截断.请参阅:PEP 238

<预><代码>>>>n = 29>>>d = 1009>>>打印 str(float(n)/d)0.0287413280476

在 Python 2(或许更早版本)中,您可以使用:

<预><代码>>>>来自 __future__ 进口部门>>>不详0.028741328047571853

Consider:

>>> numerator = 29
>>> denom = 1009
>>> print str(float(numerator/denom))
0.0

How do I make it return a decimal?

解决方案

Until version 3, Python's division operator, /, behaved like C's division operator when presented with two integer arguments: it returns an integer result that's truncated down when there would be a fractional part. See: PEP 238

>>> n = 29
>>> d = 1009
>>> print str(float(n)/d)
0.0287413280476

In Python 2 (and maybe earlier) you could use:

>>> from __future__ import division
>>> n/d
0.028741328047571853

这篇关于为什么这个除法在 Python 中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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