大一编程学生求助:找零程序循环逻辑与提示异常问题
Fixing Your Change-Making Program Issues
Hey there! Let's work through your change-making program problems step by step. I see you're dealing with two key issues: the "Insufficient funds" and "No Change" prompts not triggering when they should, plus broken logic for dispensing quarters, dimes, nickels, and pennies. Let's break down the problems and fix them.
Key Problems in Your Current Code
1. Logic Order & Float Precision Issues
- "Insufficient funds" never triggers: Your
while change_sum >= 0loop skips the check entirely whenpayment_int < in_str(sincechange_sumwould be negative). The check for insufficient funds is inside the loop, so it never runs in that case. - "No Change" fails due to float precision: Comparing floats for equality (like
payment_int == in_str) is unreliable—0.1 + 0.2doesn't equal0.3in floating-point math, so even when payment matches the price exactly, the condition might not fire. - Float calculations break coin checks: Small precision errors (e.g.,
change_sumbecoming0.009999999999999998instead of0.01) will make your penny condition fail.
2. Broken Coin Dispensing Logic
- You're using
eliffor each coin type, which means once one condition is met, the rest are skipped. For example, if you have $0.50 in change, your code will only subtract one quarter, then move to dimes instead of taking a second quarter. - The loop only handles one coin per iteration instead of maximizing the largest denomination first.
Fixed Code with Explanations
Let's rewrite the program to fix these issues, using integer cents to avoid float errors and restructuring the logic:
# Initialize coin stock (counts) quarters = 10 dimes = 10 nickels = 10 pennies = 10 print("\nWelcome to change-making program.") print(f"\nStock: {quarters} quarters, {dimes} dimes, {nickels} nickels, and {pennies} pennies") while True: # Handle user input for price, with quit option price_input = input("Enter the purchase price (xx.xx) or 'q' to quit: ") if price_input.lower() == 'q': print("Exiting program.") break try: # Convert price to cents (integer) to avoid float precision issues price_cents = int(float(price_input) * 100) except ValueError: print("Invalid input. Please enter a valid price or 'q' to quit.") continue # Get payment amount (convert to cents) try: payment_dollars = int(input("Input dollars paid (int): ")) payment_cents = payment_dollars * 100 except ValueError: print("Invalid input. Please enter an integer for dollars paid.") continue # Calculate total change needed in cents change_cents = payment_cents - price_cents # Check for insufficient funds first if change_cents < 0: print("Insufficient funds") continue # Check for no change needed elif change_cents == 0: print("No Change") continue # Now dispense change, starting with largest denomination print("\nCalculating change...") # Use quarters as much as possible while quarters > 0 and change_cents >= 25: change_cents -= 25 quarters -= 1 print(f"Used 1 quarter. Remaining change: {change_cents/100:.2f}, Quarter stock: {quarters}") # Use dimes next while dimes > 0 and change_cents >= 10: change_cents -= 10 dimes -= 1 print(f"Used 1 dime. Remaining change: {change_cents/100:.2f}, Dime stock: {dimes}") # Use nickels while nickels > 0 and change_cents >= 5: change_cents -= 5 nickels -= 1 print(f"Used 1 nickel. Remaining change: {change_cents/100:.2f}, Nickel stock: {nickels}") # Use pennies while pennies > 0 and change_cents >= 1: change_cents -= 1 pennies -= 1 print(f"Used 1 penny. Remaining change: {change_cents/100:.2f}, Penny stock: {pennies}") # Check if we couldn't dispense all change (out of coins) if change_cents > 0: print("\nSorry, not enough coins in stock to make full change.") # Print updated stock print(f"\nUpdated Stock: {quarters} quarters, {dimes} dimes, {nickels} nickels, and {pennies} pennies")
What Changed & Why?
- Integer cents instead of floats: This eliminates all precision errors—all calculations are done with whole numbers, so comparisons like
change_cents == 0work reliably. - Input validation: Added
try/exceptblocks to handle invalid user input (like non-numeric values) gracefully. - Restructured logic flow: We now check for insufficient funds or no change before trying to dispense coins, so those prompts trigger correctly.
- While loops for each coin: Instead of
elif, we use a separatewhileloop for each denomination. This ensures we use as many of the largest coin as possible before moving to smaller ones, which is the correct change-making logic. - Quit option handling: Properly implemented the 'q' quit functionality that was mentioned in the input prompt but not handled in your original code.
内容的提问来源于stack exchange,提问作者kj2k18
相关产品推荐
相关产品推荐

