You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现用户输入小数?金额类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, but int() only works for whole numbers. If someone enters a decimal like 3.99, this will throw a ValueError immediately. You need to use float() 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 elif block 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

  1. Float conversion: float() accepts both integers and decimals, so users can enter values like 2.5 or 5 without errors.
  2. Fixed total calculation: Now we multiply the unit price, the number of pounds, and the discount to get the actual amount owed.
  3. Completed discount tiers: Added an else block to handle purchases of 20 pounds or more (adjust the discount rate to match your needs).
  4. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:40:19