新编码和python。试图强制类型(int)为浮动答案

时间:2016-08-18 03:08:26

标签: python

balance = 50 - 0.12 * 15
tracks_left = balance / 0.12
round (tracks_left, 0)
print 'you have', tracks_left,"to download"

答案是you have 401.666666667 to download 我试过了round(tracks_left, 0)int (tracks_left)。 我做错了什么?

2 个答案:

答案 0 :(得分:2)

round(tracks_left, 0)不会改变tracks_left,而是返回一个新值。与int(tracks_left)同样如此。

尝试:

tracks_left = round(tracks_left, 0)

或者:

tracks_left = int(tracks_left)

注意:int总是向下舍入。

答案 1 :(得分:1)

round(tracks_left, 0)不会更改tracks_left。它只返回值。你必须把它分配给某事。

>>> balance = 50 - 0.12 * 15
>>> tracks_left = balance / 0.12
>>> tracks_left_rounded = round(tracks_left, 0)
>>> print('You have', tracks_left_rounded)
You have 402.0

你也可以这样做:

>>> balance = 50 - 0.12 * 15
>>> tracks_left = round(balance / 0.12)

您还可以尝试int

>>> tracks_left_rounded = int(tracks_left)
>>> print('You have', tracks_left_rounded)
You have 401

我希望它有所帮助!