ShadyBears
ShadyBears

Reputation: 4175

Explanation of the output of my Python code

Basically it works for almost every case I've tried besides 0.93. I then added "print money" in the while loop to see what it was doing after every loop and this was what happened:

Enter an amount less than a dollar: 0.93
0.68
0.43
0.18
0.08
0.03
0.02
0.01
3.81639164715e-17
-0.01
Your change is 3 quarters 1 dimes 1 nickels 4 pennies

Can someone explain what the hell is going on?

money = input("Enter an amount less than a dollar: ")
quarter = 0
dime = 0
nickel = 0
penny = 0

while money > 0.00:
    if money >= 0.25:
        quarter = quarter + 1
        money = money - 0.25

    elif money >= 0.10:
        dime = dime+1
        money = money - 0.10

    elif money >= 0.05:
        nickel = nickel + 1
        money = money - 0.05

    else:
        penny = penny + 1
        money = money - 0.01



print "Your change is %d quarters %d dimes %d nickels %d pennies" % (quarter, dime, nickel, penny)

Upvotes: 1

Views: 191

Answers (3)

David Howlett
David Howlett

Reputation: 109

You can't express most fractions exactly using floating point. I Think that integers are the best solution to the problem in your case. I rewrote your code to use cents and python 3.

cents = int(input("Enter a number of cents: "))
quarter = 0
dime = 0
nickel = 0
penny = 0

while cents > 0:
    if cents >= 25:
        quarter+=1
        cents-=25
    elif cents >= 10:
        dime+=1
        cents-=10
    elif cents >= 5:
        nickel+=1
        cents-=5
    else:
        penny+=1
        cents-=1
print ("Your change is %d quarters %d dimes %d nickels %d pennies" % (quarter, dime, nickel, penny)

Upvotes: 0

Tony Hopkinson
Tony Hopkinson

Reputation: 20320

amount = 93
quarters = amount // 25
amount = amount % 25
dimes = amount // 10
amount = amount * 10
nickel = amount // 5
cents = amount % 5

// is integer division. % is the modulus operator (remainder of integer division)

bit of thought you could pass in a list [25,10,5,1] and do it in a loop

Upvotes: 2

Tim Pietzcker
Tim Pietzcker

Reputation: 336078

Floating point numbers can't represent most decimal fractions exactly, just like you can't write the result of 1/3 exactly using decimal floating point notation.

Use integers to calculate with cents instead, or use the decimal module.

This has nothing to do with Python, by the way, but with the way computers generally do floating point math.

Upvotes: 14

Related Questions