修改以上代码用if语句实现
时间: 2024-09-26 20:10:23 浏览: 31
当然,我们可以将税率分段判断的部分改写成一系列`if...elif...else`语句,以下是修改后的版本:
```python
def calculate_tax(salary, insurance, other):
tax_thresholds = [3000, 12000, 25000, 35000, 55000, 80000]
tax_rates = [3, 10, 20, 25, 30, 45]
quick_deductions = [0, 210, 1410, 2660, 4410, 7160, 15160]
taxable_income = salary - 5000 - insurance - other
total_tax = 0
for threshold, rate, deduction in zip(tax_thresholds[:-1], tax_rates[:-1], quick_deductions[:-1]):
if taxable_income > threshold:
tax_amount = (taxable_income - threshold) * rate - deduction
taxable_income -= threshold
else:
tax_amount = taxable_income * rate - deduction
break
# 对于最后超过80000元的部分
if taxable_income > tax_thresholds[-1]:
tax_amount += (taxable_income - tax_thresholds[-1]) * tax_rates[-1] - quick_deductions[-1]
total_tax = max(0, tax_amount) # 确保不会支付负税
net_salary = salary - insurance - other - total_tax
return total_tax, round(net_salary, 2)
# 样例计算
income = 9000
insurance = 1234
other = 1000
tax, actual_salary = calculate_tax(income, insurance, other)
print(f"个人所得税: {f'¥{tax:.2f}'元}")
print(f"实际到手收入: {f'¥{actual_salary:.2f}'元}")
# 结果将会按上述样例输出
```
在这个版本中,我们通过嵌套的`if`语句检查每个税率段,当收入超出当前阶段时就应用新的税率和速算扣除。这种方法虽然直观,但对于较大的税率表可能会显得冗长,但如果税率层级较少,它还是一个简洁有效的解决方案。
阅读全文