python中int(x)的奇怪行为

时间:2013-08-10 03:52:44

标签: python floating-point int

运行此程序时,

cost = 12
money = 12.51
change = money - cost

dollars = int(change)
change -= dollars

quarters = int(change / 0.25)
change -= quarters * 0.25

dimes = int(change / 0.1)
change -= dimes * 0.1

nickels = int(change / 0.05)
change -= nickels * 0.05

pennies = int(change / 0.01)

print("""Your change is:
    %i dollars
    %i quarters
    %i dimes
    %i nickels
    %i pennies
""" % (dollars, quarters, dimes, nickels, pennies))

输出

Your change is:
    0 dollars
    2 quarters
    0 dimes
    0 nickels
    0 pennies

为什么便士0?我已经尝试过单独打印便士,同样的事情发生了。我也确定change / 0.01等于1.0。出于某种原因,似乎int(1.0)等于0。显然,事实并非如此。也许1.0是一个实际上不是1的浮点数,并且被0覆盖?

旁注:删除便士上的int函数并替换为%.0f pennies

我猜这正是人们在说钱时说不使用浮点数时所说的。 :)

3 个答案:

答案 0 :(得分:2)

  

我也确定知道改变/ 0.01等于1.0

嗯,不太好。如果您尝试直接从Python解释器执行change / 0.01,由于浮点错误,它会返回类似0.99999999999787的内容。当然,如果你尝试将其转换为int,它将向下舍入为零。

为避免这种情况,您可以尝试以下两种方法之一。您可以尝试使用Python中的decimal模块,它可以避免像这样的浮点错误,或者您可以在一开始就将change乘以100,这样您就可以处理整数值,而不是浮动点数,并相应地修改其余代码。

答案 1 :(得分:0)

我已完成的代码:

cost = input("What is the cost in dollars? ")
money = input("Money given: ")
change = int(round(money - cost) * 100)

if change < 0:
    print("You didn't pay enough!")
    exit()

dollars = change / 100
change %= 100

quarters = change / 25
change %= 25

dimes = change / 10
change %= 10

nickels = change / 5
change %= 5

pennies = change

print("""Your change is:
    %i dollars
    %i quarters
    %i dimes
    %i nickels
    %i pennies
""" % (dollars, quarters, dimes, nickels, pennies))

答案 2 :(得分:0)

%.0f执行数字舍入,而%i则不执行此操作。另外,学习数学!