gpt4 book ai didi

c++ - 如何在该程序中将if else语句转换为switch语句? Visual Studio 2019 C++

转载 作者:行者123 更新时间:2023-12-03 07:22:27 24 4
gpt4 key购买 nike

我已经查看了执行此操作的示例,但是当我尝试格式化这样的代码时,它不起作用。这是我要转换的程序。

#include <stdio.h> 

double comp_tax(double salary);

int
main(void)
{
double salary, tax;

printf("Input your annual salary >$ ");
scanf_s("%lf", &salary);

tax = comp_tax(salary);

if (tax != -1.0)
printf("your tax is $%.2f", tax);
else
printf("your salary is outside the table ranged");

return 0;
}

double
comp_tax(double salary)
{
double tax;

if (salary < 0.0)
tax = -1.0;
else if (salary < 15000.00)
tax = 0.15 * salary;
else if (salary < 30000.00)
tax = (salary - 15000.00) * 0.18 + 2250.00;
else if (salary < 50000.00)
tax = (salary - 30000.00) * 0.22 + 5400.00;
else if (salary < 80000.00)
tax = (salary - 50000.00) * 0.27 + 11000.00;
else if (salary <= 150000.00)
tax = (salary - 80000.00) * 0.33 + 21600.00;
else
tax = -1.0;

return (tax);
}

最佳答案

if/else大小写的顺序是更自然的表示。
如果出于某种原因必须将代码强制为switch语句,则以下可能是这种可能的混淆。

double comp_tax(double salary)
{
double tax = 0;
double ks = salary / 1000;

switch((ks > 0) * ((ks < 15) + (ks < 30) + (ks < 50) + (ks < 80) + (ks <= 150)))
{
case 1: tax += (ks - 80) * 0.33; ks = 80;
case 2: tax += (ks - 50) * 0.27; ks = 50;
case 3: tax += (ks - 30) * 0.22; ks = 30;
case 4: tax += (ks - 15) * 0.18; ks = 15;
case 5: tax += ks * 0.15; return tax * 1000;
}

return -1;
}
注意:以上内容使用给定的括号和费率来计算最高15万薪金的累进税。它不会匹配大于30K的OP的数字,因为原始代码具有可疑的“跳转”,例如 comp_tax(29999.99) == 4950comp_tax(30000.00) == 5400

关于c++ - 如何在该程序中将if else语句转换为switch语句? Visual Studio 2019 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64735191/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com