首页 文章

如何检索丢失的号码?收银机 - 确定适当的更改

提问于
浏览
0

我已经编写了这个程序,但是当我运行它时,我被缩短了一分钱 . (问题在最底层)

我的导师说这很好,因为我们还没有学会添加到字符串中的内容(?)以防止发生这种情况,但是如果我们想要的话,我们可以尝试找出要添加的内容 .

这是问题所在:

price=float(input("What is the price of the item?"))
tax=round(price*0.0725,2)
grandTotal=price+tax
tendered=float(input("How much money did customer give you?"))

print(format("The price of the item is $","26"), format(price,"6.2f"))
print(format("The tax on the item is","26"), format(tax, "6.2f"))
print(format("The total cost is","26"), format(grandTotal, "6.2f"))
print(format("You tendered","26"), format(tendered, "6.2f"))
change=tendered-grandTotal
print(format("Your change is","26"), format(change, "6.2f"))

计算变更细目

penny=int(change*100)    #transform change into pennies

dollars=penny//100       #how many dollars are there
pennyleft= penny%100     #remainder operator to find how many pennies are left

quarters= pennyleft//25 #number of quarters
pennyleft=pennyleft%25  #remainder operator to find how many pennies are left

dimes=pennyleft//10     #number of dimes
pennyleft=pennyleft%10

nickels=pennyleft//5    #number of nickels
pennyleft=pennyleft%5

pennies=pennyleft//1    #number of pennies
pennyleft=pennyleft%1
print("Your change is:")
print( format(dollars, "5"), "dollar bills,") 
print( format(quarters, "5"), "quarters,")
print( format(dimes, "5"), "dimes,")
print( format(nickels, "5"), "nickels, and")
print( format(pennies, "5"), "pennies.")

这是输出;这个商品的价格是多少?5.00你欠总共$ 5.36顾客给你多少钱?10.00该商品的价格是$ 5.00该商品的税金是0.36总费用是5.36你招标10.00你的变化是4.64你的变化是:4美元钞票,2个季度,1个角钱,0个镍币和3个便士 .

所以我的问题是3便士应该是4.任何关于如何解决这个问题的建议?

谢谢!

1 回答

  • 0

    您正在处理浮点数,因此结果可能比您预期的要多一点或多少 . 并非所有浮点数都可以精确地存储在计算机中 . 这可能听起来令人惊讶,但它与通常的十进制系统没有什么不同 . 毕竟,你也不能用十进制数字"store" 1/3 !它将是 0.3333333... (为了清晰和缺少存储空间,省略了无限量的 3 ) .

    如果您通过打印出更多小数来测试得到的值,您会发现这一行

    print(format("Your change is","26"), format(change, "6.20f"))
    

    节目

    Your change is             4.63999999999999968026
    

    并且,因为 int(x) 总是向下舍入(更具体地说,它是"truncates towards zero"(documentation)),下一行

    penny=int(change*100)
    

    只会减少多余的小数,所以最终会得到 463 . 在此之后,该数字将转换为整数,因此不会发生进一步的浮点事故 - 但为时已晚 .

    要获得正确的计算,您所要做的就是添加另一个 round

    penny=int(round(change*100))    #transform change into pennies
    

    这将偿还丢失的一分钱 .

相关问题