gpt4 book ai didi

c - 无限循环: why is this sooo endless

转载 作者:行者123 更新时间:2023-11-30 18:17:58 25 4
gpt4 key购买 nike

好的,我在这里遇到了一个小问题。不要介意代码中的注释,它们是为我准备的。

我的问题出在函数上。我希望对其进行测试以再次确保 [0] = y 或 n。如果它不循环,直到我输入正确的数字。

现在它做了什么:无论我输入什么,它都会无限循环。

我是否错过了什么,我确信它错过了。

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <cstdio>

//functions called
float wages_loop();

//start main
int main(void)
{
char status[10], another[10];
char buffer[80];

float wages, other_income, interest, dividends, test;
int dependents;
int single_acc = 0, mj_acc = 0, ms_acc = 0, sh_acc = 0;

printf("Would you like to start: ");
gets_s(another);

while (another[0] = 'y')
{
//printf("What is your Status: ");
//gets_s(status);


wages = wages_loop();



//printf("\n How much in Other Income. ");
//gets_s(buffer);
//other_income = atof(buffer);

//printf("\n How much in interest. ");
//gets_s(buffer);
//interest = atof(buffer);

//printf("\n How much in Dividends. ");
//gets_s(buffer);
//dividends = atof(buffer);

//printf("\n How many Dependents. ");
//gets_s(buffer);
//dependents = atoi(buffer);

printf("\n\n\t\t Your wage is: %.2f \n", wages);
system("pause");
} //end loop

printf("\n\n\t\t\t Number of Singles filleing: %i \n", single_acc);

return 0;

}//end main


float wages_loop()
{
char again[10];
char buffer[80];
float wages, total_wages = 0;

printf("\n How much in Wages. ");
gets_s(buffer);
wages = atof(buffer);

total_wages = wages + total_wages;

printf("\n Do you have any more wages. (y or n)");
gets_s(again);

if (again[0] != 'y' || 'n')
{
while (again[0] != 'y' || 'n')
{
printf("\n\n INCORRCT ANSWER. \n\n");
printf("\n Do you have any more wages. (y or n)");
gets_s(again);
}
}

while (again[0] = 'y')
{
printf("\n Enter Wages: ");
gets_s(buffer);
wages = atof(buffer);

total_wages = wages + total_wages;

printf("\n Do you have any more wages. ");
gets_s(again);
}

return total_wages;
}

最佳答案

while (another[0] = 'y')

这是赋值,而不是相等。将 = 更改为 ==

编辑:你在这里又做了一次:

while (again[0] = 'y')

另外:

(again[0] != 'y' || 'n')

应该是

(again[0] != 'y' && again[0] != 'n')

因为 'n' 本身总是返回 true

(感谢乔纳森·汉森)

编辑2:正如山姆在评论中指出的那样,您没有在循环中设置another[0],因此即使您将运算符更改为 ==,添加语句以再次抓取用户输入。

EDIT3:正如 log0 指出的那样,您可以通过调高编译器上的警告级别来避免将来出现此问题。

关于c - 无限循环: why is this sooo endless,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21863309/

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