我正在编写一个简单的代码来计算应付的更改量,并使用print语句来检查我的值。
cost = float(raw_input('How much did your meal cost? > '))
payment = float(raw_input('How much did you pay? > '))
change = (payment - cost)
print change
if change < 0:
print 'You need to pay $%.2f more!' % (-change)
dollars, q, d, n, p = 0, 0, 0, 0, 0
change = float(change*100)
print change
if change> 100:
dollars = int(change/100)
change = change % 100
print change
if change >= 25:
q = int(change/25)
change = change % 25
print change
if change >= 10:
d = int(change/10)
change = change % 10
print change
if change >= 5:
n = int(change/5)
change = change % 5
print change
if change >= 1:
p = int(change/1)
else:
print "why doesn't this work?"
print p
print change
print 'you get %d dollars, %d quarters, %d dimes, %d nickels, and %d pennies!' % (dollars, q, d, n, p)
返回:
您的餐费是多少? &GT; 34.34
你付多少钱? &GT; 40
5.66
566.0
66.0
16.0
6.0
1.0
为什么这不起作用?
0
1.0
我可以在便士计算之前和之后看到变化= 1.0,但是
if change >= 1
仍然显示为false,并转到else语句。这里发生了什么,我该如何解决?
答案 0 :(得分:3)
欢迎使用IEEE 754浮点数。享受inaccuracies。如果要避免它们,请使用定点或整数机制。
答案 1 :(得分:1)
答案 2 :(得分:0)
浮子(40)-float(34.34)= 5.659999999999997
我猜你说“change = 1.0”不是1.0,而是0.99999999999
尝试:round(40-34.34, 2)
答案 3 :(得分:0)
正如伊格西奥所说的那样。简单的解决方法就是抛出一条线来改变第二个小数位。使用函数简化一些事情,您的代码变为:
def get_change_and_coin(coin_amount, change):
change = round(change, 2)
return (change % coin_amount, int(change / coin_amount))
cost = float(raw_input('How much did your meal cost? > '))
payment = float(raw_input('How much did you pay? > '))
change = (payment - cost)
print change
if change < 0:
print 'You need to pay $%.2f more!' % (-change)
dollars, q, d, n, p = 0, 0, 0, 0, 0
dollars = int(change)
change = float(change*100)
(change, q) = get_change_and_coin(25, change)
(change, d) = get_change_and_coin(10, change)
(change, n) = get_change_and_coin(5, change)
(change, p) = get_change_and_coin(1, change)
print 'you get %d dollars, %d quarters, %d dimes, %d nickels, and %d pennies!' % (dollars, q, d, n, p)
希望这有帮助!