简体   繁体   中英

New to programming class (python 3.4) Coin change issue

I'm doing the coin change problem (Taking a specific US dollar amount, and converting it into how many quarters, dimes, nickels, and pennies that is.)

I'm hung up on converting the amount. I'll put in $0.50 and get no results, but inputting 50 gives me 2 quarters. Where am I going wrong?

#!/usr/bin/env python3

#Display information about program
print("Change Calculator")
print()

#Input Data
choice = "y"
while choice.lower() == "y":
    dollarAmount = float(input("Enter dollar amount (for example, .56, 7.85): $"))
    if dollarAmount <= 0:
        print("Danger Will Robinson, Danger! Only positive numbers work! Try again")
        print()
    else:    
        print() #Displays correct amount of change
        print(dollarAmount//25, "Quarters: ")
        dollarAmount = dollarAmount%25
        print(dollarAmount//10, "Dimes: ")
        dollarAmount = dollarAmount%10
        print(dollarAmount//5, "Nickels: ")
        dollarAmount = dollarAmount%5
        print(dollarAmount//1, "Pennies: ")
        print()
        if dollarAmount >= 0:
            choice = input("Would you like to enter another amount? (y/n): ")
            print()

print("Goodbye!! May the force be with you.")

You are using dollarAmount as if it were the number of cents, which is why it works when you enter the amount in cents. If you want to enter the amount in dollars, you need to convert it to cents before performing your change computation.

dollarAmount needs to be treated as an amount in cents. As I explained in my comment, you can do this by multiplying the amount by 100. See code below for where I would make the change.

#!/usr/bin/env python3

#Display information about program
print("Change Calculator")
print()

#Input Data
choice = "y"
while choice.lower() == "y":
    dollarAmount = float(input("Enter dollar amount (for example, .56, 7.85): $"))
    if dollarAmount <= 0:
        print("Danger Will Robinson, Danger! Only positive numbers work! Try again")
        print()
    else:
        #Convert to cents 0.56 -> 56
        dollarAmount = dollarAmount * 100
        print() #Displays correct amount of change
        print(dollarAmount//25, "Quarters: ")
        dollarAmount = dollarAmount%25
        print(dollarAmount//10, "Dimes: ")
        dollarAmount = dollarAmount%10
        print(dollarAmount//5, "Nickels: ")
        dollarAmount = dollarAmount%5
        print(dollarAmount//1, "Pennies: ")
        print()
        if dollarAmount >= 0:
            choice = input("Would you like to enter another amount? (y/n): ")
            print()

print("Goodbye!! May the force be with you.")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM