1

我正在编写一个简单的代码来计算应发生多少变化,并使用打印语句来检查我的值。

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)

这将返回:

你的一顿饭花了多少钱?> 34.34

你付了多少钱?> 40

5.66

566.0

66.0

16.0

6.0

1.0

为什么这不起作用?

0

1.0

我可以在便士计算之前和之后看到 change = 1.0,但是

if change >= 1

仍然读为假,并转到 else 语句。这里发生了什么,我该如何解决?

4

4 回答 4

3

欢迎使用 IEEE 754 浮点。享受不准确之处。如果您想避免它们,请使用定点或整数机制。

于 2013-07-22T03:13:18.223 回答
1

请阅读:浮点算术:问题和限制

http://docs.python.org/2/tutorial/floatingpoint.html

你可能对十进制模块感兴趣

于 2013-07-22T03:24:06.850 回答
0

浮动(40)-浮动(34.34)=5.659999999999997

我猜你说“change = 1.0”不是1.0,而是0.99999999999

尝试:round(40-34.34, 2)

于 2013-07-22T03:19:41.597 回答
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)

希望这可以帮助!

于 2013-07-22T03:25:09.627 回答