我正在用C做一个简单的猜测游戏,但是当猜测正确时,它不会退出循环。问一个愚蠢的问题,但我是新来的C。下面是一个代码的副本,如果有人可以帮助,谢谢。
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <stdbool.h>
int getGuess()
{
int guess;
printf("Enter your guess: ");
scanf("%d", &guess);
return guess;
}
int playGuessingGame()
{
int guess = getGuess();
int answer = sqrt(rand() % 100 + 10);
bool solved = false;
while (!solved)
{
if (guess == answer)
{
printf("You got it!\n");
solved = true;
break;
}
else if (guess < answer)
{
printf("To Low!\n");
guess = getGuess();
}
else
{
printf("To High!\n");
guess = getGuess();
}
}
return 0;
}
int main(void)
{
printf("Welcome to the guessing game!\n");
while (1) // infinite loop
{
printf("\nEnter Y to play or Q to quit: "); // ask for each iteration
char input;
scanf(" %c", &input); // Use " %c" to consume leading whitespace left over.
if (input == 'Q') // break infinite loop
{
break;
}
if (input == 'Y')
{
playGuessingGame();
}
else
{
printf("Invalid input\n");
}
}
}
我正试图使它只通过打印语句,它不要求再次猜测。
1条答案
按热度按时间smdncfj31#
重新排列
main()
的代码: