#include<stdio.h>
#include<ctype.h>
#define EXTRA_HOUR 1.5f //额外的小时
#define BASE_TAX 0.15f //基础的税率
#define EXTRA_TAX 0.2f //额外的税率
#define EXCEED_TAX 0.25f //超额税的税率
int menu(void); //菜单函数
int get_choice(void); //获取选择函数
void eatline(void); //清空多余字符的函数
float data_l(float ch, float n); //计算工资总额的函数
float tax_l(float data); //计算税率的函数
int main(void)
{
int ch;
float n, add, tax;
while ((ch = menu()) != 'q')
{
printf("Enter the working hours a week: ");
while (scanf_s(" %f", &n) != 1 || n < 0)
{
eatline();
printf("Please,enter a ture number: ");
}
switch (ch)
{
case 'a':
add = data_l(8.75f, n);
tax = tax_l(add);
break;
case 'b':
add = data_l(9.33f, n);
tax = tax_l(add);
break;
case 'c':
add = data_l(10.00f, n);
tax = tax_l(add);
break;
case 'd':
add = data_l(11.20f, n);
tax = tax_l(add);
break;
}
printf("The total salary is:%.3f\n", add);
printf("Tax is: %.3f\n", tax);
printf("Net income is: %.3f", add - tax);
}
return 0;
}
int menu(void) //菜单
{
char ch;
printf("\n");
for (int i = 0; i <= 100; i++)
putchar('*');
printf("\nEnter the number corresponding to the desired pay rate or action:\n");
printf("a) $8.75/hr\t\tb) $9.33/hr\nc) $10.00/hr\t\td) $11.20/hr\nq) quit\n");
for (int i = 0; i <= 100; i++)
putchar('*');
printf("\nPlease enter you choose: ");
ch = get_choice();
if (islower(ch) == 0) //检查是否为小写字母
{
printf("Please,enter lowercase letters: ");
ch = get_choice();
}
else if (ch != 'a' && ch != 'b' && ch != 'c' && ch != 'd' && ch != 'q')
{
printf("Please,enter a ture choice(a,b,c,d or q): ");
ch = get_choice();
}
return ch;
}
int get_choice(void) //读取选择
{
char ch;
scanf_s(" %c", &ch);
eatline();
return ch;
}
void eatline(void) //请除多余的输入
{
while (getchar() != '\n')
continue;
return;
}
float data_l(float ch,float n)//工资总额计算
{
float data;
if (n <= 40)
data = n * ch; //40小时内的基础工资计算
else
data = n * 1.5 * ch; //40小时后时间为1.5倍
return data;
}
float tax_l(float data) //税收计算
{
float ch;
if (data <= 300) //前300美元为15%
ch = data * BASE_TAX;
else if (data <= 450) //续150美元为20%
ch = 300 * BASE_TAX + (data - 300) * EXTRA_TAX;
else //余下的为25%
ch = 300 * BASE_TAX + 150 * EXTRA_TAX + (data - 450);
return ch;
}
用多个自定义函数来实现相对应的功能,进行相关修改时会简单点,阅读性也会增强。
这代码基于vs2019写的,部分函数会在其他编译器会报错,类似scanf,vs为了安全要写成这样:scanf_s,删点相应的部分就可以了。