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

Python3 销售税与账单计算(第二部分):价格两位小数格式化报错求助

解决方法

你当前没有对输入完成后的price变量做格式化打印,input()的提示语仅用于引导输入,不会自动将输入的数值转换为两位小数格式输出,因此无法得到你想要的效果。

只需在获取price变量后新增一行格式化打印语句即可,以下是可直接运行的修改后代码,完全沿用你原本的format()写法逻辑:

price = float(input("Price: $ "))
# 新增格式化打印价格的逻辑
print("Price: $", format(price, '.2f'))
tax = .05
salestax = price * tax
total = salestax + price
print("Sales Tax: $", format(salestax,'.2f'))
print("Total: $", format(total,'.2f'))

如果偏好更简洁的f-string写法,也可以替换为如下版本,效果完全一致:

price = float(input("Price: $ "))
print(f"Price: ${price:.2f}")
tax = .05
salestax = price * tax
total = salestax + price
print(f"Sales Tax: ${salestax:.2f}")
print(f"Total: ${total:.2f}")

如果不想要输入前的引导提示和后续格式化打印的Price行重复,可以把input的提示内容改为空字符串:price = float(input("")),运行时直接输入数值即可得到完全匹配你给出示例的输出效果。


内容的提问来源于stack exchange,提问作者Matt Triano

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 03:42:02