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

Python编写周薪计算程序时加班费计算结果错误求助

周薪核算代码问题排查与修复

存在的3个核心错误

  • 条件判断逻辑错误:第二个分支用了or逻辑,应该改为and。hours > 40 or hours < 50的判断规则下,所有大于40的数值都会命中该分支,超出50小时的工时永远不会进入第三个分支核算
  • 变量名错误:第三个分支中,你定义的超50小时工时变量为othours,后续计算时误写为不存在的othours2
  • 变量覆盖与计算逻辑错误:第三个分支中,你先定义了前10小时加班的1.5倍薪资otpay,后续又将otpay重新赋值为超50小时的2倍薪资,直接覆盖了原有1.5倍加班费;最终求和时重复加了两次otpay,逻辑完全错误

修正后代码

def weeklypaycheck(hours, rate):
    if hours <= 40:
        pay = hours * rate
        print("This is your pay: ", pay)
    elif 40 < hours <= 50:
        normal_pay = 40 * rate
        ot_hours = hours - 40
        ot_pay = ot_hours * rate * 1.5
        print("This is your pay: ", normal_pay + ot_pay)
    else:
        normal_pay = 40 * rate
        first_ot_pay = 10 * rate * 1.5
        second_ot_hours = hours - 50
        second_ot_pay = second_ot_hours * rate * 2
        total_pay = normal_pay + first_ot_pay + second_ot_pay
        print("This is your pay: ", total_pay)

测试验证

  • 输入weeklypaycheck(55,10):4010 + 1015 + 5*20 = 400 + 150 + 100 = 650.0,符合预期
  • 输入weeklypaycheck(51,20):4020 + 1030 + 1*40 = 800 + 300 +40 = 1140.0,符合预期

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 18:36:05