BASIC C循环-当另一个if语句为true时,为什么我的代码的else部分正在运行

时间:2018-11-18 12:44:46

标签: c

我对编程非常陌生,并且正在通过一些C基础工作。我正在尝试编写一些非常简单的使用条件语句的代码。该程序的目的是采用先前定义的最大可能数字和最小可能数字,然后将其除以二,然后询问用户是否正在考虑该数字。如果其值太高,则会对其进行更改;如果值太低,则会对其进行更改,然后再次询问。最后的说明是输入的三个字母以外的内容。

但是,当我启动这段代码时。它说第一个printf语句,即“不是有效答案”的printf语句,然后在等待用户输入之前重复第一个printf语句。这发生在每个开始循环中。 (有关输入,请参见下文)。

是否需要更改我的循环的格式?请记住,我已经编码了大约4周。谢谢!

//initiate a loop until the program guesses the right thing

do{
    guess = (lowest_possible + highest_possible)/2;
    printf("my guess is %d,am I right (Y) too high (H) or too low(L)?: ", guess);
    char user_response = getchar();
    if (toupper(user_response) == 'Y') {
        guess_check = 1;
    }
    else if(toupper(user_response) == 'H'){
        highest_possible = guess - 1;
        printf("Hmmm too high? Let me guess again. \n");
    }
    else if(toupper(user_response) == 'L'){
        lowest_possible = guess +1;
        printf("Hmmm too low? Let me guess again. \n");
    }
    else {
        printf("That's not a valid answer, please try again. \n");
    }
 }while(guess_check == 0);

输出:

my guess is 50,am I right (Y) too high (H) or too low(L)?: That's not a valid answer, please try again. 

my guess is 50,am I right (Y) too high (H) or too low(L)?:  H
That's not a valid answer, please try again. 

my guess is 50,am I right (Y) too high (H) or too low(L)?: Hmmm too high? Let me guess again. 

my guess is 25,am I right (Y) too high (H) or too low(L)?: That's not a valid answer, please try again. 

my guess is 25,am I right (Y) too high (H) or too low(L)?: 

0 个答案:

没有答案