如何实现用户输入小数?金额类Python程序报错求助
Fixing Your Decimal Input & Price Calculation Issues
Hey there! Let's walk through the problems in your code and get it working properly for decimal inputs and accurate price calculations.
Key Issues in Your Current Code
- Wrong type conversion for decimals: You're using
int()to convert user input, butint()only works for whole numbers. If someone enters a decimal like3.99, this will throw aValueErrorimmediately. You need to usefloat()instead to handle decimal values. - Incorrect price calculation logic: Your code is multiplying the unit price by the discount, but you're not factoring in the number of pounds purchased. The total price should be
unit price × pounds × discount. - Truncated code: Your last
elifblock is cut off (price = p…), so we'll need to complete that logic. - Clunky string concatenation: Using
str()to combine strings and numbers works, but f-strings are cleaner and more readable for formatting outputs.
Corrected Code
# Get user input and convert to floats to handle decimals unit_price = float(input("What is the price of your vegetable per pound? ")) pounds_purchased = float(input("How many pounds did you buy? ")) # Calculate total with tiered discounts if pounds_purchased < 5: total_price = unit_price * pounds_purchased * 1.0 # No discount elif pounds_purchased < 10: total_price = unit_price * pounds_purchased * 0.90 # 10% off elif pounds_purchased < 20: total_price = unit_price * pounds_purchased * 0.80 # 20% off (adjust as needed) else: total_price = unit_price * pounds_purchased * 0.70 # Larger discount for bulk orders # Print formatted total (2 decimal places for currency) print(f"Your total price is ${total_price:.2f}")
What Changed & Why
- Float conversion:
float()accepts both integers and decimals, so users can enter values like2.5or5without errors. - Fixed total calculation: Now we multiply the unit price, the number of pounds, and the discount to get the actual amount owed.
- Completed discount tiers: Added an
elseblock to handle purchases of 20 pounds or more (adjust the discount rate to match your needs). - Formatted output:
f"${total_price:.2f}"ensures the total is displayed as currency with exactly two decimal places, which is standard for money-related programs.
内容的提问来源于stack exchange,提问作者Jerry Cui
相关产品推荐
相关产品推荐

