否则如果条件优先于条件?

时间:2018-03-26 19:20:09

标签: c

请原谅这个初学者的问题。我刚刚开始编程,我在下面的代码中使用了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(answer!=' c'))。在我的输出中,即使我输入了' c,它也会在最后一个"中输出错误语句。关于正确的阻止和声明。

这是输出:

 Invalid. Please use either h (too high), l (too low) or c (correct). The computer has guessed the correct answer!

在“c'进入?

谢谢!

1 个答案:

答案 0 :(得分:2)

您的程序的声明按C标准预定义的顺序执行。这包括计算while / do循环的while条件。

循环在到达循环体的末端时检查条件。这包括执行循环内的所有if语句及其else分支。由于您对循环中的'c' 没有特殊处理,if (answer != '\n')分支会被执行,并提供您看到的打印输出。

您可以通过使用“forever”循环并在其正文中处理'c'输入来解决此问题:

for (;;) {
    answer = getchar();
    if (answer == 'c')  {
        break;
    }
    ... // The rest of your code goes here
}