小费计算器出现TypeError:字符串与浮点数无法执行除法运算
错误原因
你把计算后的带小费总账单转换成了字符串:
billWithTip = str(tip / 100 * bill + bill)
之后将这个字符串赋值给totalBill,后续尝试用它除以people(浮点数类型),Python不支持字符串与浮点数执行除法运算,因此触发TypeError。
修正后的代码
print("Welcome to the tip calculator!") bill = float(input("What was the total bill? £")) tip = int(input("how much tip would you like to leave? 10, 12, or 15?")) # 保留数值类型,不提前转字符串 billWithTip = tip / 100 * bill + bill # 打印时再转为字符串拼接 print("the final price is £" + str(billWithTip)) totalBill = billWithTip # 人数用int转换更合理,因为人数是整数 people = int(input("how many people should split the bill?")) totalBill2 = totalBill / people print(totalBill2)
可选优化
- 对最终人均金额做格式化,保留两位小数,更贴合金额显示逻辑:
print(f"Each person needs to pay: £{totalBill2:.2f}")
内容的提问来源于stack exchange,提问作者R0ckTillWeDr0p
相关产品推荐
相关产品推荐

