python基础:python2.7 浮点数操作常见“陷阱”

2016-12-08  本文已影响0人  莫等闲空

刚接触Python2.7 进行除法运算可能会感动很奇怪:

>>> 3/2
1
>>> 10/3
3
>>> 

结果为整数?
思考了一会,你可能会这样改进

>>> float(3)/2
1.5
>>> float(10)/3
3.3333333333333335
>>> 

恩恩,这样的确解决了少数部分被"抛弃"的现象,但float(10)/3这样的精度可能不是你希望的。
这里给你推荐函数round(x,n)

>>> help(round)
Help on built-in function round in module __builtin__:

round(...)
    round(number[, ndigits]) -> floating point number
    
    Round a number to a given precision in decimal digits (default 0 digits).
    This always returns a floating point number.  Precision may be negative.
>>> 

请思考下面这段两端代码会输出什么:

#coding=utf-8

i = 1
k = 1

while i != 1.5:
    i += 0.1
    k += 1
    if k == 10:
        print 'See you'
        break
        
print  'The value of i is {0}'.format(i)
#coding=utf-8

i = 1
k = 1

while round(i,1) != 1.5:
    i += 0.1
    k += 1
    if k == 10:
        print 'See you'
        break

print  'The value of i is {0}'.format(i)

如果得出正确答案,恭喜你!else,请看下面比较具体的解答(注:截图来自《Python核心编程》):


20160609002255281.png
上一篇 下一篇

猜你喜欢

热点阅读