请原谅这个初学者的问题。我刚刚开始编程,我正在使用 C 作为下面的代码。
此代码的目的是让计算机猜测用户选择的数字。计算机将根据"太低"或"太高"等队列缩小可用数字的范围。
computer_guess(int answer)
{
int lownum, highnum, guess, answer;
//Instructions
printf("Please use 'h' for too high or 'l' for too low ");
printf("for incorrect guess. Use 'c' if the guess is right.n");
guess = (lownum + highnum)/2;
printf("n %d. n", guess);
printf("Is this the right number?");
do
{
answer = getchar();
if (answer == 'h')
{
guess = (lownum + (highnum -1))/2;
printf("%d n", guess);
}
else if (answer == 'l') //If the computer's guess is too high.
{
guess = ((lownum + 1) + highnum)/2;
printf("%d n", guess);
}
else if (answer != 'n')//If the user enters letters other than 'h' or 'l', an error message will be returned.
{
fflush(stdin);
printf("Invalid. Please use either h (too high), l (too low) or c (correct).");
}
} while (answer != 'c');
if (answer == 'c')//If the correct answer is given, the game will end.
{
printf("The computer has guessed the right number.");
}
return 0;
}
我遇到的问题是我的代码似乎忽略了我的 while 条件(while (答案 != 'c'))。在我的输出中,即使我输入"c",它也会在最后一个"else if"块中打印 Error 语句和关于正确的语句。
这是输出:
Invalid. Please use either h (too high), l (too low) or c (correct). The computer has guessed the correct answer!
我需要做什么来确保输入"c"时不会打印错误?
谢谢!
程序的语句按照 C 标准预定义的顺序执行。这包括计算do
/while
循环的while
条件。
循环在到达循环主体的末端时检查条件。这包括执行循环内的所有if
语句及其else
分支。由于您对循环内的'c'
没有特殊处理,因此if (answer != 'n')
分支将被执行,并提供您看到的打印输出。
您可以通过使用"永久"循环并在其正文中处理'c'
输入来解决此问题:
for (;;) {
answer = getchar();
if (answer == 'c') {
break;
}
... // The rest of your code goes here
}