python 的两种除法

更新日期: 2017-06-16 阅读次数: 14213 分类: Python

Python 除法运算符 '/' 与 '//' 的区别

>>> 10 / 3
3
>>> 10 // 3
3
>>> 10 / 3.0
3.3333333333333335
>>> 10 // 3.0
3.0
>>> type(10 // 3.0)
<type 'float'>

也就是当除数和被除数都是整数的时候,返回结果都是整数。 当除数和被除数至少有一个是浮点数的时候,返回结果都是浮点数。但是, // 的结果的小数部分永远是 0.

`Floor division'' is what Python's / operator currently does when given integer operands; the result is the floor of the value returned by true division. ``Classic division'' is the current mixed behaviour of /; it returns the result of floor division when the operands are integers, and returns the result of true division when one of the operands is a floating-point number.

Here are the changes 2.2 introduces:

A new operator, //, is the floor division operator. (Yes, we know it looks like C++'s comment symbol.) // always performs floor division no matter what the types of its operands are, so 1 // 2 is 0 and 1.0 // 2.0 is also 0.0.

参考:http://docs.python.org/release/2.2.3/whatsnew/node7.html

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式