C猜谜游戏,循环错误

pgky5nke  于 2023-10-16  发布在  其他
关注(0)|答案(1)|浏览(104)

我正在用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");
        }
    }
}

我正试图使它只通过打印语句,它不要求再次猜测。

smdncfj3

smdncfj31#

重新排列main()的代码:

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

int main( void )
{
    srand(time(NULL)); // seed the random number generator.

    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.
        // credit @SomeProgrammerDude

        if (input == 'Q') // break infinite loop
        {
            break;
        }
        if (input == 'Y')
        {
            playGuessingGame();
        }
        else
        {
            printf("Invalid input\n");
        }
    }
}

相关问题