day*_*mer 1 python rounding division python-2.x integer-division
我在分手时遇到了问题
my max_sum = 14
total_no=4
Run Code Online (Sandbox Code Playgroud)
所以,当我这样做
print "x :", (total_sum/total_no)
Run Code Online (Sandbox Code Playgroud)
,我得到3而不是3.5
我尝试了很多方法进行打印但是失败了,有人能让我知道我用3.5格式的方式吗?
谢谢
在Python 2.x中,默认情况下将两个整数划分为另一个整数.这通常令人困惑,并已在Python 3.x中修复.您可以通过将其中一个数字转换为浮点数来绕过它,它会自动转换另一个数字:
float( 14 ) / 4 == 3.5
相关的PEP是238号:
The current division (/) operator has an ambiguous meaning for numerical arguments: it returns the floor of the mathematical result of division if the arguments are ints or longs, but it returns a reasonable approximation of the division result if the arguments are floats or complex. This makes expressions expecting float or complex results error-prone when integers are not expected but possible as inputs.
It was not changed in Python 2.x because of severe backwards-compatibility issues, but was one of the major changes in Python 3.x. You can force the new division with the line
from __future__ import division
Run Code Online (Sandbox Code Playgroud)
at the top of your Python script. This is a __future__-import -- it is used to force syntax changes that otherwise might break your script. There are many other __future__ imports; they are often a good idea to use in preparation for a move to Python 3.x.
Note that the // operator always means integer division; if you really want this behaviour, you should use it in preference to /. Remember, "explicit is better than implicit"!