剛接觸Python2.7 進行除法運算可能會感動很奇怪:
>>> 3/2
1
>>> 10/3
3
>>>
結果為整數(shù)?
思考了一會贺归,你可能會這樣改進
>>> float(3)/2
1.5
>>> float(10)/3
3.3333333333333335
>>>
恩恩淆两,這樣的確解決了少數(shù)部分被"拋棄"的現(xiàn)象,但float(10)/3這樣的精度可能不是你希望的牧氮。
這里給你推薦函數(shù)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核心編程》):