自动售货机找零计算器开发问题:硬币分解逻辑与输入校验需求
Let's tackle this problem head-on. First, let's diagnose why your nickel and penny calculation is off, then build out the full solution with input validation to make the tool robust.
Why the 87 input is giving wrong results
When you input 87, here's what should happen mathematically:
- 87 ÷ 25 = 3 quarters (totaling 75), leaving 12 cents
- 12 ÷ 10 = 1 dime (totaling 10), leaving 2 cents
- 2 ÷ 5 = 0 nickels, leaving 2 pennies
Your current code is probably miscalculating the remaining amount after dimes—maybe you're forcing a nickel count even when the remainder isn't large enough, or mixing up division and modulo operations. Let's fix that with clean, step-by-step logic.
Full Solution Code
Here's a Python implementation that handles both the correct change breakdown and input validation:
def calculate_change(amount): # Calculate each coin type using integer division and modulo quarters = amount // 25 remaining = amount % 25 dimes = remaining // 10 remaining = remaining % 10 nickels = remaining // 5 pennies = remaining % 5 # Whatever's left after nickels is pennies # Helper to handle pluralization for clean output def pluralize(count, coin_name): return f"{count} {coin_name}{'s' if count != 1 else ''}" return ", ".join([ pluralize(quarters, "quarter"), pluralize(dimes, "dime"), pluralize(nickels, "nickel"), pluralize(pennies, "penny") ]) def get_valid_input(): while True: user_input = input("Enter the amount in cents (positive integer): ") try: amount = int(user_input) if amount >= 0: return amount else: print("Error: Please enter a non-negative integer.") except ValueError: print("Error: That's not a valid integer. Please try again.") # Run the full program if __name__ == "__main__": valid_amount = get_valid_input() change_breakdown = calculate_change(valid_amount) print(f"Change breakdown: {change_breakdown}")
Key Fixes & Explanations
- Correct coin math: We use
//(integer division) to get how many of each coin fits into the remaining amount, then%(modulo) to capture what's left after using that coin type. This ensures we never over-count nickels or pennies. - Input validation: The
get_valid_inputloop keeps asking for input until the user provides a non-negative integer. It handles both non-numeric inputs (like text) and negative values gracefully. - Polished output: A small helper function ensures we use "penny" instead of "pennies" when there's exactly one, and vice versa for other coins—this makes the output feel more natural.
Testing the 87 Input
If you run this code and enter 87, you'll get the expected output:
Change breakdown: 3 quarters, 1 dime, 0 nickels, 2 pennies
内容的提问来源于stack exchange,提问作者onedimensional_noob

