'/' 和 '//' 用于除法时有什么区别? [英] What is the difference between '/' and '//' when used for division?

查看:32
本文介绍了'/' 和 '//' 用于除法时有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用一个比另一个有好处吗?在 Python 2 中,它们似乎都返回相同的结果:

<预><代码>>>>6/32>>>6//32

解决方案

在 Python 3.x 中,5/2 将返回 2.55//2 将返回 2.前者是浮点除法,后者是整除法,有时也称为整数除法.>

在 Python 2.2 或更高版本的 2.x 行中,整数没有区别,除非您执行 from __future__ import Division,这会导致 Python 2.x 采用 3.x 行为.

无论以后导入如何,5.0//2 将返回 2.0 因为这是操作的楼层划分结果.

您可以在 https 上找到详细说明://docs.python.org/whatsnew/2.2.html#pep-238-changed-the-division-operator

Is there a benefit to using one over the other? In Python 2, they both seem to return the same results:

>>> 6/3
2
>>> 6//3
2

解决方案

In Python 3.x, 5 / 2 will return 2.5 and 5 // 2 will return 2. The former is floating point division, and the latter is floor division, sometimes also called integer division.

In Python 2.2 or later in the 2.x line, there is no difference for integers unless you perform a from __future__ import division, which causes Python 2.x to adopt the 3.x behavior.

Regardless of the future import, 5.0 // 2 will return 2.0 since that's the floor division result of the operation.

You can find a detailed description at https://docs.python.org/whatsnew/2.2.html#pep-238-changing-the-division-operator

这篇关于'/' 和 '//' 用于除法时有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆