优化这段代码#include <stdio.h> int main() { int salary; double tax = 0.0; // 个人所得税额 printf("请输入您的工资:"); scanf("%d",&salary); int taxable = salary - 1600; // 应纳税所得额 if (taxable <= 0) { printf("您不需要缴纳个人所得税.\n"); } else if (taxable > 0 && taxable <= 500) { tax = taxable * 0.05; } else if (taxable > 500 && taxable <= 2000) { tax = 25 + (taxable - 500) * 0.1; } else if (taxable > 2000 && taxable <= 5000) { tax = 175 + (taxable - 2000) * 0.15; } else if (taxable > 5000 && taxable <= 20000) { tax = 625 + (taxable - 5000) * 0.2; } else if (taxable > 20000 && taxable <= 40000) { tax = 3625 + (taxable - 20000) * 0.25; } else if (taxable > 40000 && taxable <= 60000) { tax = 8625 + (taxable - 40000) * 0.3; } else if (taxable > 60000 && taxable <= 80000) { tax = 14625 + (taxable - 60000) * 0.35; } else if (taxable > 80000 && taxable <= 100000) { tax = 21625 + (taxable - 80000) * 0.4; } else if (taxable > 100000) { tax = 29625 + (taxable - 100000) * 0.45; } printf("您的工资是%d元,应当缴纳个人所得税%d元.\n", salary, (int)tax); return 0; }
时间: 2024-03-30 16:38:12 浏览: 37
#include <stdio.h>
这段代码已经非常简单,但还是可以进行一些优化。以下是一些可能的优化点:
1. 增加注释:为了让代码更易读和易理解,可以增加一些注释来解释代码的作用和流程。
2. 使用浮点数计算:个人所得税额通常是一个浮点数,因此可以将变量“tax”声明为“double”类型,从而提高计算精度。
3. 优化判断条件:如果使用“else if”语句,可以将条件判断的次数减少到8次,从而提高代码的可读性和效率。
以下是优化后的代码:
```c
#include <stdio.h>
int main() {
int salary;
double tax = 0.0; // 个人所得税额
printf("请输入您的工资:");
scanf("%d", &salary);
int taxable = salary - 1600; // 应纳税所得额
if (taxable <= 0) {
printf("您不需要缴纳个人所得税.\n");
} else if (taxable <= 500) {
tax = taxable * 0.05;
} else if (taxable <= 2000) {
tax = 25 + (taxable - 500) * 0.1;
} else if (taxable <= 5000) {
tax = 175 + (taxable - 2000) * 0.15;
} else if (taxable <= 20000) {
tax = 625 + (taxable - 5000) * 0.2;
} else if (taxable <= 40000) {
tax = 3625 + (taxable - 20000) * 0.25;
} else if (taxable <= 60000) {
tax = 8625 + (taxable - 40000) * 0.3;
} else if (taxable <= 80000) {
tax = 14625 + (taxable - 60000) * 0.35;
} else {
tax = 21625 + (taxable - 80000) * 0.4;
}
printf("您的工资是%d元,应当缴纳个人所得税%.2f元.\n", salary, tax);
return 0;
}
```
这段代码比原来的代码更加简洁和易读,而且使用了浮点数来计算个人所得税额,提高了计算精度。
阅读全文