Python入门编写薪资计算程序时总扣除额未计入税款问题求助
问题排查结果
核心错误原因
- 税款计算逻辑错误,问题出在
tax_total = int(gross_salary)*int(tax_rate)这行代码
你定义的tax_rate = .10是浮点型数值,调用int()方法转换时会直接舍弃小数部分,最终得到0,因此tax_total的计算结果始终为0。你在计算total_deductions时相当于加了一个0值,自然总扣除额只会统计SSS、PhilHealth、住房贷款三项的总和,不会计入税款。 - 关于你提到的净薪资数值正确的情况,按照你贴出的代码逻辑,净薪资实际是未扣税的数值,出现和预期一致的情况属于测试用薪资数据巧合导致的偶发匹配,并非代码逻辑本身正确。
修复方案
修改税款计算行,去掉对tax_rate的int()转换即可,同时建议提前统一数值类型避免重复转换、减少精度损失,参考修改后的代码:
print("=================DEDUCTIONS=================") # 提前将字符串类型的金额转为数值,避免后续重复转换 sss = int(sss_contribution) philhealth = int(philhealth_contribution) housing = int(housing_loan) gross = int(gross_salary) print("SSS: " + str(sss)) print("PhilHealth: " + str(philhealth)) print("Other Loan: " + str(housing)) tax_rate = .10 tax_total = gross * tax_rate print("Tax: " + str(tax_total)) total_deductions = sss + philhealth + housing + tax_total print("Total Deductions: " + str(total_deductions)) net_salary = gross - total_deductions print("NET SALARY: " + str(net_salary))
如果需要更简洁的字符串拼接方式,也可以用Python的f-string语法,不需要反复调用str()转换,写法更不易出错:
print(f"SSS: {sss}") print(f"PhilHealth: {philhealth}") print(f"Other Loan: {housing}")
内容的提问来源于stack exchange,提问作者Nika
相关产品推荐
相关产品推荐

