python中的//和round()之间的差异

发布于 2025-02-12 16:29:49 字数 133 浏览 2 评论 0原文

使用//(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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

时光沙漏 2025-02-19 16:29:50

// IS flo Floor division,回合回合到最近的//始终保持整数,回合使用/转换为float之前,这可能无法正常工作对于int s,根本可能会失去较小(但仍然大的)int s的精度。

如果您需要int s的地板划分,始终使用//(也可以使用进行天花板部门,( - NUM) // div))。总是正确的,其中roundMath.floor)可能不是(对于int S超过53位)。 回合更可配置(您可以将其四舍五入到指定数量的小数位数,包括小数点的小数点,可以在小数点的左侧四舍五入),但是您需要避免转换为float毫无疑问。

// is floor division, round rounds to nearest. // stays integer at all times, round using / converts to float before rounding back, which might not work at all for large enough ints, and can lose precision for smaller (but still large) ints.

If you need floor division of ints, always use // (you can do ceiling division too, with -(-num // div)). It's always correct, where round (and math.floor) might not be (for ints 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 to float at all whenever you can.

柳若烟 2025-02-19 16:29:50
>>> 5 // 2
2
>>> round(5 / 2)
2
>>> round(5 / 2, 1)
2.5
>>>

回合功能使您可以更多地控制舍入的精度。 //操作员提供了两者的地板(圆形)。

另请考虑:

>>> round(20 / 3)
7
>>> 20 // 3
6
>>>
>>> 5 // 2
2
>>> round(5 / 2)
2
>>> round(5 / 2, 1)
2.5
>>>

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:

>>> round(20 / 3)
7
>>> 20 // 3
6
>>>
清引 2025-02-19 16:29:50

//rough()是两种不同的东西。
//是划分的,然后是地板
Round()是使浮点数短的函数。

>>> 10 // 3   # 10 divide to 3, then floor
3
>>> round(10 / 3, 2)   # 10 divide to 3, take 2 number after the dot
3.33

// and round() are two different things.
// is divide, then floor
round() is a function to make a float number shorter.

>>> 10 // 3   # 10 divide to 3, then floor
3
>>> round(10 / 3, 2)   # 10 divide to 3, take 2 number after the dot
3.33
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文