程序用可以存储4个int类型的数组存储税率薪资分界线{17850, 23900, 29750, 14875},
分别对应4 种类型的人{“signal”, “house holder”, “married”, “divorced”},程序读取用户输入的
类型(1,2,3,4)和税前工资,再将类型对应的薪资分界和薪资作为参数传递给计算薪资的函数
Wage_Compute(int,int),函数返回用户应该教的个人所得税,最后将结果打印到终端。
本程序没有使用 if else 或者 switch 语句来根据用户输入的类型(1~4)来选择对应的
薪资分界,而是直接将用户输入的数字当作数组下表,这样使用户输入与目标挂钩。
如果用常规的分类讨论,那么嘚进行两轮讨论,用户类型和薪资是否超过薪资
分界线,如此写的嵌套代码,可读性大大降低。
#include// #define SIGNAL 17850 // #define HOLDER 23900 // #define MARRIED 29750 // #define DIVORCED 14875 #define RATE_LESS 0.15 #define RATE_MORE 0.28 float Wage_Compute(int , int); //function declaration int main(void) { const int edge[4] = { 17850, 23900, 29750, 14875 }; //the edge of wage const char *type[4] = {"signal", "house holder", "married", "divorced"}; int choice, wage; printf("Enter the tax type of you(1 to 4, others to quit):n"); printf("1) %-15s%20c2) %-15sn","signal", ' ',"house holder"); printf("2) %-15s%20c3) %-15sn", "married", ' ', "divorced"); printf("Which is right for you: "); if (scanf("%d", &choice) != 1 || choice > 4 || choice < 1) { printf("Input error!n"); return -1; } printf("Enter your wage: "); if(scanf("%d", &wage)!=1) { printf("Input error!n"); return -1; } float tax = Wage_Compute(edge[choice - 1], wage); // send the value of choice pointing printf("Your wage is $%d, and you are %s, so you need pay $%.2f" " for tax,therefore, you will get $%.2f in the end.n",wage,type[choice-1],tax,wage-tax); printf("Done!n"); return 0; } float Wage_Compute(int choice, int wage) //function definition { float tax; switch(wage>choice) { case 1: tax = (wage - choice) * RATE_MORE + wage * RATE_LESS; break; case 0: tax = wage * RATE_LESS; break; } return tax; }
下面是程序运行的部分示例



