您的位置:首页 > 编程语言 > Python开发

python int() round() floor()函数的比较

2018-02-23 19:38 344 查看
猛的一看  int() round()  math.floor() 这几个函数函数好像做的是同一件事情,很容易将他们弄混,下面是他们的一些不同之处:int()函数直接截去小数部分
floor() 得到最接近原数但是小于原数的部分
round()得到最接近原数的整数(返回为浮点类型)
如下面的例子:import math
for eachnum in (.2,.7,1.2,1.7,-.2,-.7,-1.2,-1.7):
 print"int(%.1f)\t%+.1f"%(eachnum,float(int(eachnum)))
 print"floor(%.1f)\t%+.1f"%(eachnum,math.floor(eachnum))
 print "round(%.1f)\t%+.1f"%(eachnum,round(eachnum))
 print'-'*20>>> 
int(0.2) +0.0
floor(0.2) +0.0
round(0.2) +0.0
--------------------
int(0.7) +0.0
floor(0.7) +0.0
round(0.7) +1.0
--------------------
int(1.2) +1.0
floor(1.2) +1.0
round(1.2) +1.0
--------------------
int(1.7) +1.0
floor(1.7) +1.0
round(1.7) +2.0
--------------------
int(-0.2) +0.0
floor(-0.2) -1.0
round(-0.2) -0.0
--------------------
int(-0.7) +0.0
floor(-0.7) -1.0
round(-0.7) -1.0
--------------------
int(-1.2) -1.0
floor(-1.2) -2.0
round(-1.2) -1.0
--------------------
int(-1.7) -1.0
floor(-1.7) -2.0
round(-1.7) -2.0
--------------------
>>>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息