python中的//和round()之间的差异
使用//
(Integer Division)和python中的内置函数之间有区别吗?如果我正确理解,两者都将四处往最近的整数,但是我不确定函数和操作员的行为是否始终是完全相同的。有人可以澄清吗?它们俩都可以“互换”使用吗?
Is there a difference between using //
(Integer Division) and the built-in round()
function in Python? If I understand correctly, both will round to the nearest Integer but I'm unsure if the behaviour of both the function and the operator is exactly the same at all times. Can someone clarify? Can both of them be used "interchangeably"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
//
IS flo Floor division,回合
回合到最近的。//
始终保持整数,回合
使用/
转换为float
之前,这可能无法正常工作对于int
s,根本可能会失去较小(但仍然大的)int
s的精度。如果您需要
int
s的地板划分,始终使用//
(也可以使用进行天花板部门,( - NUM) // div)
)。总是正确的,其中round
(Math.floor
)可能不是(对于int
S超过53位)。回合
更可配置(您可以将其四舍五入到指定数量的小数位数,包括小数点的小数点,可以在小数点的左侧四舍五入),但是您需要避免转换为float
毫无疑问。//
is floor division,round
rounds to nearest.//
stays integer at all times,round
using/
converts tofloat
before rounding back, which might not work at all for large enoughint
s, and can lose precision for smaller (but still large)int
s.If you need floor division of
int
s, always use//
(you can do ceiling division too, with-(-num // div)
). It's always correct, whereround
(andmath.floor
) might not be (forint
s exceeding about 53 bits).round
is more configurable (you can round off to a specified number of decimal places, including negative decimal places to round off to the left of the decimal point), but you want to avoid converting tofloat
at all whenever you can.回合
功能使您可以更多地控制舍入的精度。//
操作员提供了两者的地板(圆形)。另请考虑:
The
round
function gives you more control over the precision of rounding. The//
operator provides the floor (rounds down) of dividing the two.Consider also:
//
和rough()
是两种不同的东西。//
是划分的,然后是地板Round()
是使浮点数短的函数。//
andround()
are two different things.//
is divide, then floorround()
is a function to make a float number shorter.