我在while中的while循环无法正常工作。我得到它的方式设置它并没有开始y催化后。请有人帮我这个吗
#include <stdio.h>
#pragma warning(disable:4996)
#include <stdlib.h>
#include <time.h>
void play_game();
int main()
{
char resp;
printf("Welcome to the game of Guess It!\n\n");
printf("I will choose a number between 1 and 100.\n");
printf("You will try and guess that number.If you guess wrong, I\n");
printf("will tell you if you guessed too high or too low.\n\n");
printf("You have six tries to guess the number.\n\n");
play_game();
printf("Would you like to play again? (y/n)\n");
scanf("%c%*c",&resp);
while((resp=='y') || (resp=='Y'))
{
play_game();
printf("Would you like to play again?\n");
scanf("%c%*c",&resp);
}
printf("Goodbye it was fun.\n");
printf("Hope to play Guess It with you again soon.\n");
return 0;
}
void play_game()
{
int num;
int guess = 0;
int count = 1;
count =1;
srand((unsigned int)time(NULL));
num = rand() % 100 +1;
printf("Ok I am thinking of a number. Try to guess it.\n");
printf("Your guess?\n");
scanf("%d",&guess);
while(guess != num && count != 6)
{
if(guess > 100 || guess < 1)
{
printf("Illegal guess. Your guess must be between 1 and 100.\n");
printf("Guess again\n");
scanf("%d", &guess);
count ++;
}
else if(guess > num)
{
printf("Too High! Guess again\n");
scanf("%d", &guess);
count ++;
}
else if(guess < num)
{
printf("Too Low! Guess again\n");
scanf("%d", &guess);
count ++;
}
}
if (guess == num)
{
printf("***CORRECT***\n");
}
else
printf("Too many guesses\n");
printf("The number is %d\n\n", num);
}
答案 0 :(得分:0)
也许您可以在play_game函数内的scanf中添加“%* c”,以排出输入数字后可能正在输入的换行符。
答案 1 :(得分:0)
尝试将"%c%*c"
更改为"%c\n"
。
scanf()正在扫描你的键盘。我假设您想在进入印刷机后停止扫描。因此换行符“\ n”,它对应于enterpress。
您也可以使用do while而不是while。这样你只需要编写一次重复的代码。例如:
do
{
play_game();
printf("Would you like to play again?\n");
scanf("%c%*c",&resp);
} while((resp=='y') || (resp=='Y'))
这样,在检查条件之前执行du body内部的代码。