为什么这个部门在Python中不起作用? [重复]

时间:2021-07-08 07:03:27

This question already has an answer here:

这个问题在这里已有答案:

Consider:

考虑:

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

How do I make it return a decimal?

如何让它返回小数?

4 个解决方案

#1


26  

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

在版本3之前,Python的除法运算符/在表示两个整数参数时表现得像C的除法运算符:它返回一个整数结果,当有一个小数部分时,它会被截断。见:PEP 238

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

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

在Python 2中(可能更早),您可以使用:

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

#2


8  

In Python 2.x, division works like it does in C-like languages: if both arguments are integers, the result is truncated to an integer, so 29/1009 is 0. 0 as a float is 0.0. To fix it, cast to a float before dividing:

在Python 2.x中,除法与C语言类似:如果两个参数都是整数,则结果被截断为整数,因此浮点数为0.0时,29/1009为0。要修复它,在分割之前施放到浮子:

print str(float(numerator)/denominator)

In Python 3.x, the division acts more naturally, so you'll get the correct mathematical result (within floating-point error).

在Python 3.x中,除法行为更自然,因此您将获得正确的数学结果(在浮点错误内)。

#3


1  

In your evaluation you are casting the result, you need to instead cast the operands.

在您的评估中,您正在转换结果,您需要转换操作数。

#4


0  

print str(float(numerator)/float(denom))

#1


26  

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

在版本3之前,Python的除法运算符/在表示两个整数参数时表现得像C的除法运算符:它返回一个整数结果,当有一个小数部分时,它会被截断。见:PEP 238

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

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

在Python 2中(可能更早),您可以使用:

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

#2


8  

In Python 2.x, division works like it does in C-like languages: if both arguments are integers, the result is truncated to an integer, so 29/1009 is 0. 0 as a float is 0.0. To fix it, cast to a float before dividing:

在Python 2.x中,除法与C语言类似:如果两个参数都是整数,则结果被截断为整数,因此浮点数为0.0时,29/1009为0。要修复它,在分割之前施放到浮子:

print str(float(numerator)/denominator)

In Python 3.x, the division acts more naturally, so you'll get the correct mathematical result (within floating-point error).

在Python 3.x中,除法行为更自然,因此您将获得正确的数学结果(在浮点错误内)。

#3


1  

In your evaluation you are casting the result, you need to instead cast the operands.

在您的评估中,您正在转换结果,您需要转换操作数。

#4


0  

print str(float(numerator)/float(denom))