比ı找到答案之后。我得到2倍的问题,即“ Excellent!。喜欢再次玩(y或no);。即使我写y或n。问题也不会改变取决于答案。(顺便说一句,我为我的英语不好对不起。
我试图将该语句的位置(if(answer ..)更改为while的第一行或结束行或类似的东西。此外,我还尝试了在某处放置中断(我认为问题不会这,但我尝试过。)
int main() {
srand(time(NULL));
int guess,number;
char answer;
number=1+(rand()%1000);
printf("I have a number between 1 and 1000\n");
printf("Could you guess my number?\n");
printf("Please type your guess\n");
while(1) {
scanf("%d",&guess);
if(guess==number) {
printf("Excellent!You guessed the number!Would you like to play again(y or n)");
scanf("%c",&answer);
if(answer=='y') {
number=1+(rand()%1000);
printf("I have a number between 1 and 1000 \n");
printf("Could you guess my number? \n");
printf("Please type your guess \n");
}
else if(answer=='n') {
return 1;
}
}
else if(guess>number){
printf("Too high.Try again.\n");
}
else if(guess<number){
printf("Too low.Try again.\n");
}
}
}
答案 0 :(得分:1)
在您的代码中,将从控制台输入的以下两个语句将被执行:
scanf("%d",&guess);
...
scanf("%c",&answer);
执行scanf("%d",&guess);
时,它将从stdin中读取一个数字,但是它将在缓冲区中保留最后一个新行(您必须在缓冲的stdin中输入该行以完成输入)。后续的scanf("%c",&answer);
将立即在此新行中读入answer
,而不会给用户提供输入任何其他字母的机会。
写...
scanf(" %c",&answer);
使得在读取“实际”字符之前会消耗掉所有空白。