【Python】Python2/3中的除法和round()的初步使用

python2和python3对比

Python2.X和3.X的除法是不一样的,相比之下,Python2的除法简直坑爹…
花了大半个小时整理下:
测试环境为:Python2.7,Python3.6.
测试工具:Windows7下的Pycharm.
虽然8021年了,但是有些时候还是用Python2.X.
下面的#后面为输出结果,按着顺序写的.上面的是第一个print的结果,第二个为第二个print的结果.

python2实例:

c=12
d=24
print c/d
print c//d
# 0
# 0

c=12
d=24
print c%d
# 12

c = 12.0
d = 24
print c/d
print c//d
# 0.5
# 0

c = 12.0
d = 24
print c%d
# 12.0

c = 12
d = 24.0
print c/d
print c//d
# 0.5
# 0

c = 12
d = 24.0
print c%d
# 12.0

c=12
d=24
e=float(c)/float(d)
print e
e=float(c)//float(d)
print e
# 0.5
# 0.0

Python2 round()使用(单个参数的使用):

在Python2中使用round(),在只使用一个参数,不指定位数的时候,返回一个最靠近的整数,在最后一个为.5的时候,会向上四舍五入.

round(0.5)
1.0
round(1.5)
2.0
round(2.5)
3.0

这里使用的cmd测试的.

Python3实例:

c=12
d=24
print(c/d)
print(c//d)
# 0.5
# 0

c=12
d=24
print(c%d)
# 12

c = 12.0
d = 24
print(c/d)
print(c//d)
# 0.5
# 0.0

c = 12.0
d = 24
print(c%d)
# 12.0

c = 12
d = 24.0
print(c/d)
print(c//d)
# 0.5
# 0.0

c = 12
d = 24.0
print(c%d)
# 12.0

c=12
d=24
e=float(c)/float(d)
print(e)
e=float(c)//float(d)
print(e)
# 0.5
# 0.0

Python3 round()使用(单个参数的使用):

Python3的round()中总体而言是和Python2中使用一致,只有在最后一位为.5的时候,是向最近的偶数靠近,比如:

round(1.5)
2
round(2.5)
2
round(0.5)
0

但是如果不是.5结束的:比如

round(1.53)
2
round(2.53)
3

这里使用的cmd测试的.

round()两个参数的使用:

上面都只是一个参数,如果是两个参数
使用两个参数的时候(一个是要处理的参数,一个是指定小数点后位数的)

当指定位数的时候,一般情况也是使用四舍五入的规则,只有在碰到最后一位为.5的情况,如果要取舍的位数前的小数是奇数直接舍弃,如果偶数这向上取整。
例子:

Python 2
print(round(2.675,2)) >> 2.67
print(round(2.765,2)) >> 2.77

Python3
也是一样的结果

Python 3
print(round(2.675,2))  >> 2.67
print(round(2.765,2))  >> 2.77

猜你喜欢

转载自blog.csdn.net/lvluobo/article/details/80993008