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

如何使用for循环、range与列表实现员工薪资计算多记录正确输出

问题原因

  • 没有初始化列表存储每位员工的工时和薪资数据,输入循环中num_hrs_worked变量每次被新输入覆盖,仅保留最后一次输入值
  • 薪资计算逻辑、打印逻辑缩进错误,不在输入循环内部,不会为每个员工单独执行计算
  • 超出40小时的薪资计算逻辑不符合规则,当前是全工时按1.5倍计算,正确应为40小时内按基础时薪,超出部分按1.5倍计算

修改后代码

def calculate_total_pay_cad(num_employees, hrly_rate_CAD):
    # 初始化存储员工信息的列表
    employee_pay_list = []
    for _ in range(num_employees):
        num_hrs_worked = int(input('Input the number of worked hours: '))
        # 按规则计算薪资
        if num_hrs_worked <= 40:
            pay = num_hrs_worked * hrly_rate_CAD
        else:
            pay = 40 * hrly_rate_CAD + (num_hrs_worked - 40) * hrly_rate_CAD * 1.5
        # 将当前员工的工时和薪资存入列表
        employee_pay_list.append((num_hrs_worked, pay))
    # 遍历列表输出结果,保留两位小数
    for hours, earned in employee_pay_list:
        print(f"the employee worked for {hours} hours and the earned is {earned:.2f}$")

num_employees = int(input('enter number employees: '))
hrly_rate_CAD = int(input('enter hourly rate: '))

calculate_total_pay_cad(num_employees, hrly_rate_CAD)

测试验证

输入员工数2、时薪10的运行结果:

Input the number of worked hours: 60
Input the number of worked hours: 20
the employee worked for 60 hours and the earned is 700.00$
the employee worked for 20 hours and the earned is 200.00$

和预期输出完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 23:15:08