python中`//`运算符的用途是什么?

Lel*_*uge 8 python operators

可能重复:
在Python中使用'//'的原因是什么?

//运营商的目的是什么?

x=10
y=2
print x/y
print x//y

两者都5作为值输出.

Joh*_*Jr. 22

整数除法与浮动除法:

>>> 5.0/3
3: 1.6666666666666667
>>> 5.0//3
4: 1.0
Run Code Online (Sandbox Code Playgroud)

或者,正如他们在Python文档中所说的那样,//是"x和y"的"(浮动)商".上面的例子是在Python 2.7.2中运行的,它只对浮点数采用这种方式.如果你在2.7.2中使用整数,你会得到:

>>> 5/3
9: 1
>>> 5//3
10: 1
Run Code Online (Sandbox Code Playgroud)

在Python 3.x中你会得到不同的结果,所以如果你真的想要使用floored版本,//那就养成使用某天的习惯了:

Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 5/3
1.6666666666666667
>>> 5//3
1
>>> 5.0/3
1.6666666666666667
>>> 5.0//3
1.0
Run Code Online (Sandbox Code Playgroud)

  • 特殊+1用于养成使用//的习惯,因为某天它很重要: (2认同)