python 回合问题

标签 python rounding division python-2.x integer-division

我在划分的时候遇到了问题

my max_sum = 14
total_no=4  

所以当我这样做的时候

print "x :", (total_sum/total_no)

,我得到 3 而不是 3.5

我尝试了很多打印方式但都失败了,有人可以告诉我我用什么方式打印 3.5 格式吗?

谢谢

最佳答案

在 Python 2.x 中,默认情况下将两个整数相除会得到另一个整数。这常常令人困惑,并且已在 Python 3.x 中修复。您可以通过将其中一个数字转换为 float 来绕过它,这将自动转换另一个:

float ( 14 )/4 == 3.5

相关的 PEP 是 number 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.

由于严重的向后兼容性问题,它在 Python 2.x 中没有更改,但它是 Python 3.x 中的主要更改之一。你可以用这条线强制新部门

from __future__ import division

在 Python 脚本的顶部。这是 __future__-import -- 它用于强制更改语法,否则可能会破坏您的脚本。还有许多其他的 __future__ 导入;在准备迁移到 Python 3.x 时使用它们通常是个好主意。

请注意,// 运算符始终表示整数除法;如果你真的想要这种行为,你应该优先使用它而不是 /。请记住,“显式优于隐式”!

关于 python 回合问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3621717/

相关文章:

python - 索引 1 超出轴 0 的范围,决策树分类的大小为 1 错误

python - 获取模块 py 文件路径的可靠方法

python - python 中的 pandas 显示数据框的全部内容

php - PHP 中特定小数位的小数舍入

python - 将一个数分成(几乎)相等的整数的算法

python - Python 2.7在python中同时解码UTF-8和unicode-escape会导致UnicodeEncodeError

我可以使用舍入来确保原子浮点运算的确定性吗?

java - 如何避免 double 的舍入错误?

Python:在 double_scalars 中捕获运行时溢出

c# - 在哪里重载除法返回自定义类 C# operator/(int,int)