gpt4 book ai didi

c++ - 为什么我的 if else 不起作用?

转载 作者:搜寻专家 更新时间:2023-10-30 23:58:04 26 4
gpt4 key购买 nike

我得到了一个不错的二维数组小函数。我想在第一个数组中搜索收入,然后使用相同的 int 在二维数组中找到正确的数字。

我已将我的问题限制在一行代码中。 if Else 语句在 for 循环中不起作用。我不知道为什么。任何没有用锤子敲打它的想法。

   float get_total_income( float income)
{
char status[10];
float over_income = 30001;
float final_rate = .35;
float adjusted_income = 0;
int check = -1;
int x = 0;
float rate;
float array_income[] = { 6000.00, 9000.00, 15000.00, 21000.00, 25000.00, 30000.00 };

float rates[][6] = { { .028, .075, .096, .135, .155, .174 }, { 0.0, .052, .083, .122, .146, .163 },
{ .023, .072, .089, .131, .152, .172 }, { 0.0, .038, .074, .110, .138, .154 } };


printf("\n\t YOUR INCOME AFTER DEPENDANTS: %.2f", income);


while (check < 0)
{
printf("\n\n\nEnter your Status (S, MJ, MS, SH)");
gets_s(status);

if (status[0] == 'S' && status[1] == '\0')
{
single_total = single_total + 1;
check = 0;
}
else if (status[0] == 'M' && status[1] == 'J')
{
mj_total = mj_total + 1;
check = 1;
}
else if (status[0] == 'M' && status[1] == 'S')
{
ms_total = ms_total + 1;
check = 2;
}
else if (status[0] == 'S' && status[1] == 'H')
{
sh_total = sh_total + 1;
check = 3;
}
else
{
printf("\n\n INCORRECT STATUS. Enter (S, MJ, MS, or SH) \n\n");
}
}


if (income > over_income)
{
rate = final_rate;
}
else
{
for (x = 0; x<6; x++)
{
printf("num %i# \n", x);

if (income <= array_income[x])
{
rate = rates[check][x];
printf("\t\nworks, %i# in loop answer: %.3f\n",x, rate);
}
}//end for loop
}//end if

printf("\n\t YOUR TAX RATE: %.3f", rate);

return rate;
}

这部分:

for (x = 0; x<6; x++)
{
printf("num %i# \n", x);

if (income <= array_income[x])
{
rate = rates[check][x];
printf("\t\nworks, %i# in loop answer: %.3f\n",x, rate);
}

它不是一次停止打印,而是打印整个表格。由于某种原因,If 语句在这里没有作用,编译器将忽略它。

应该发生的是IF income = 2000 且 <= income_array它应该打印数组的那一部分。然而,它只是继续前进,就像条件总是真实的一样。

最佳答案

你永远不会中断你的循环,所以它总是会运行到结束。如果您想在条件为真时立即停止迭代,请使用以下代码:

for (x = 0; x<6; x++)
{
printf("num %i# \n", x);

if (income <= array_income[x])
{
rate = rates[check][x];
printf("\t\nworks, %i# in loop answer: %.3f\n",x, rate);
break;
}
}

关于c++ - 为什么我的 if else 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21985579/

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