首先注明:如果没有特别说明,以下内容都是基于python 3.4的。
先说核心要点:
1. /是精确除法,//是向下取整除法,%是求模
2. %求模是基于向下取整除法规则的
3. 四舍五入取整round, 向零取整int, 向下和向上取整函数math.floor, math.ceil
4. //和math.floor在CPython中的不同
5. /在python 2 中是向下取整运算
6. C中%是向零取整求模。
如果你对上面这几点都很熟悉,那么就不要浪费时间往下看了,珍惜生命,远离泛滥的灌水文章!
大纲如下:
1. 一个测试程序和它的输出
2. 取整和求模运算规则
3. python中其他的取整运算
4. //和math.floor在CPython中的不同
5. 运算符/在python 2 和python 3 中的区别
6. 其他讨论(求余和求模)
下面按顺序介绍:
1. 一个测试程序和它的输出
测试程序如下(python 3.4):
print('usage of 3 operators /, // and % in python 3.4')
print('1). usage of /')
print ('10/4 = ', 10/4)
print ('-10/4 = ', -10/4)
print ('10/-4 = ', 10/-4)
print ('-10/-4 = ', -10/-4)
print('\n2). usage of //')
print ('10//4 = ', 10//4)
print ('-10//4 = ', -10//4)
print ('10//-4 = ', 10//-4)
print ('-10//-4 = ', -10//-4)
print('\n3). usage of %')
print ('10%4 = ', 10%4)
print ('-10%4 = ', -10%4)
print ('10%-4 = ', 10%-4)
print ('-10%-4 = ', -10%-4)
输出结果如下:
u