0
Sometimes it works. Why?
This code works with anything under a $1.51 difference. But if the change is $1.51 or over, it doesn't D: CODE: while True: print("This is a change calculator!") print("Enter the amount of money the item costs!") itemCost = float(input('
#x27;)) print("Enter the amount of money you will pay!") payment = float(input('#x27;)) changeAmount = payment - itemCost amountOfQuarters = changeAmount/.25 amountOfDollars = int(amountOfQuarters/4) print("Dollars:", int(amountOfDollars)) print("Quarters:", int(amountOfQuarters) - int(amountOfDollars * 4)) amountAfterQuarters = changeAmount - (int(amountOfQuarters) * .25) amountOfDimes = amountAfterQuarters/.10 print("Dimes:", int(amountOfDimes)) afterDimesQuarters = changeAmount - ((int(amountOfQuarters) * .25) + \(int(amountOfDimes) * .10)) amountOfNickels = afterDimesQuarters/.05 print("Nickels:", int(amountOfNickels)) afterNickels = changeAmount - ((int(amountOfQuarters) * .25) + (int(amountOfDimes\ ) * .10) + (int(amountOfNickels) * .05)) amountOfPennies = afterNickels/.01 print("Pennies:", int(amountOfPennies))4 odpowiedzi
+ 6
The problem seems to be in using int(amountOfPennies).
Enter the amount of money the item costs!
$4.99
Enter the amount of money you will pay!
$10
20.04
Dollars: 5
Quarters: 0
"Dimes:" 0.09999999999999787
Dimes: 0
"Nickels:" 0.19999999999999574
Nickels: 0
"Pennies:" 0.9999999999999787
Pennies: 0
since the float is 0.9999999999999787, when you use int() on it, it always rounds it down to 0. Try using round() instead. Also troubleshoot the rest of the code since int() is used everywhere and it will likely cause the same issues with all parts of the code (:
+ 5
What exactly isn't working? Is there some kind of error or does the code not produce expected results?
0
Oh sorry forgot to say. Its 1 cent off at times.
0
Since penny is the lowest denomination, the variable "amountOfPennies" in the 2nd last line will always have an integer value, and therefore you don't have to use int() or round() to output the result. You can safely remove the int() function in the last line and it will show you the expected result.
And to optimize the code, I would use the int() function to convert the values of variables (such as amountOfDimes, amountOfNickels etc) to integer "upfront", so that I don't have to write int(amountOfDimes), int(amountOfNickels) etc on all the references later in the code.
A fun solid program otherwise. Happy coding!