如何找回丢失的号码?确定收银机的适当位置

2024-09-30 01:27:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经写了程序,但当我运行它时,我得到了一分钱的短缺。(问题在最底层)

我的教练说这很好,因为我们还没有学会在弦上加什么(?)为了防止这种情况发生,但他说,如果我们愿意的话,我们可以试着找出要添加的内容。你知道吗

问题是:

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 你总共欠5.36美元 顾客给了你多少钱?10 这件商品的价格是5美元 这个项目的税是0.36英镑 总成本是5.36美元 你出价10.00 找你的零钱是4.64英镑 您的零钱是: 4美元钞票, 2个季度, 一毛钱, 0个镍币,还有 3便士。你知道吗

所以我的问题是3便士应该是4。关于如何解决这个问题有什么建议吗?你知道吗

谢谢你!你知道吗


Tags: oftheformatnumberischangepricetax
1条回答
网友
1楼 · 发布于 2024-09-30 01:27:02

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

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

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

演出

Your change is             4.63999999999999968026

而且,由于int(x)总是向下舍入(更具体地说,它“向零截断”(documentation)),下一行

penny=int(change*100)

只切断多余的小数,这样你就得到了463。在这之后,数字被转换成整数,这样就不会再发生浮点错误了——但为时已晚。你知道吗

要获得正确的计算结果,您只需添加另一个round

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

这将补偿那一分钱的损失。你知道吗

相关问题 更多 >

    热门问题