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

Python小费计算器开发遇TypeError:字符串与整数无法执行除法

问题分析与解决

错误根源

  1. 类型运算不兼容:在percent_to_float函数里,你移除%后的p还是字符串类型,直接和整数100做除法,字符串与整数无法进行算术运算,这就是触发TypeError的原因。
  2. 缺少返回值:你的两个自定义函数只执行了print操作,没有用return返回转换后的值,导致main函数里的dollars和percent变量拿到的是None,就算修复第一个错误,后续相乘仍会报错。

修正后的代码

def dollars_to_float(d):
    d = d.replace("$", "")
    df = float(d)
    return df  # 返回转换后的餐费数值

def percent_to_float(p):
    p = p.replace("%", "")
    pf = float(p) / 100  # 先把字符串转为float,再除以100得到小费比例
    return pf  # 返回转换后的小费比例

def main():
    dollars = dollars_to_float(input("How much was the meal? "))
    percent = percent_to_float(input("What percentage would you like to tip? "))
    tip = dollars * percent
    print(f"Leave ${tip:.2f}")

main()

测试示例

输入餐费$50、小费比例15%,程序会输出Leave $7.50,运行正常。

内容的提问来源于stack exchange,提问作者Brianna Orz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 21:36:26