程序无法识别if-else语句中的字符输入

时间:2015-04-27 12:47:16

标签: c arrays if-statement char logical-operators

我调试了程序并发现虽然您输入了一个选项,例如Y/y/n/NH/h/l/L,但if函数无法识别输入,并且它会跳过。谢谢你的建议! RNG工作正常,一切似乎都没问题。

#include <stdio.h>
#include <time.h>



 int main(){
char startAnswer[1];
char gameAnswer[1];
int i;
int r;
int t;
int compare;
srand(time(NULL));

printf("Do you want to play a game? Y/N. \n");
scanf(" %c", &startAnswer);
start:
if (startAnswer == 'y' || 'Y'){
    goto game;
}
else if (startAnswer == 'n' || 'N'){
    printf("Game will now exit.\n");
}
else {
    printf("You entered an invalid answer, try again.\n");
    goto start;
}
game:
printf("There will be ten numbers calculated.\n");
printf("Try to guess what the numbers are before\n");
printf("they are displayed. One at a time.\n\n");
for(i = 0; i < 12; i++){

    randGen:
    r = ( rand() % 9 ) + 1;
    t = ( rand() % 9 ) + 1;
    if(t == r){
        goto randGen;
    }

    printf("Is the next number higher or lower than %d\n\n" , r);
    scanf(" %c" , &gameAnswer);
 //ignore       (r > t) ? (compare = 0) : (compare = 1);
    if (r > t){
        compare = 1;
    }
    else{
        compare = 0;
    }



    if (gameAnswer == ('H' || 'h')){
        if (compare == 1){
            printf("You win this round!");
            goto randGen;
        }
    }
    else if (gameAnswer == ('L' || 'l')){
        if (compare == 0){
            printf("You win this round!");
            goto randGen;
        }
    }
    else if (gameAnswer != ('l' || 'L' || 'h' || 'H')){
        if (compare == 0){
            printf("Please Enter H/L for higher/lower answer.\n\n");
            goto randGen;
        }
    }
    else{
            printf("You lost this round.");
            goto randGen;
    }
    r = t;

}



}

5 个答案:

答案 0 :(得分:3)

在您的代码中

if (gameAnswer == ('H' || 'h'))

不符合您的想法。将其更改为

if ((gameAnswer[0] == 'H')  || (gameAnswer[0] == 'h'))   //gameAnswer is an array

同样,对于所有其他事件。

另外,

scanf(" %c", &startAnswer);

应该是

scanf(" %c", &startAnswer[0]);

同样

注意:

  1. 如果您不需要 array请勿使用。坚持一个变量。

  2. main()的推荐签名为int main(void)

  3. 只是一个建议,请尝试避免goto声明。它不被认为是一种好习惯。尝试编写和使用函数。

答案 1 :(得分:0)

if (startAnswer == 'y' || 'Y'){

没有。这不是如何连锁条件。 You are translating broken English into C++.

答案 2 :(得分:0)

有很多问题:

其中一个是:

(a,b)

哪些是

char startAnswer[1];
char gameAnswer[1];

你的编译器肯定会在这里发出警告。

答案 3 :(得分:0)

您的代码有两个问题:

  1. if条件,例如:if (gameAnswer == ('H' || 'h')),应该是:if (gameAnswer == 'H' || gameAnswer=='h')

  2. charschar startAnswer[1]; char gameAnswer[1];执行此操作:char startAnswer; char gameAnswer;或:在代码中使用gameAnswer[0]代替gameAnswer

  3. 最后,对于srandrand,您需要添加stdlib库,只需添加以下行:#include<stdlib.h>http://www.cplusplus.com/reference/cstdlib/srand/

答案 4 :(得分:-1)

您在阅读该选项之前使用的是fflush(stdin)吗?这将清理你的缓冲区。