Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

Simple guessing game in c

Hello I'm trying to write a simple number guessing game in c. If the player guesses the number correctly, the program will give a message and aks if the player want to play again.

When i compile the code, it generate the random number, let the player guess the number and check whether the number is right or not. But when it aks if the player want to play again, it does not let the player answer and instead just exit. I don not know why it happens. Can you please help me?

int main()
{ 

int number, guess_value,number_of_guesses;
char answer;

srand((unsigned)time(NULL));
number=rand() %100+1;

A:number_of_guesses=0;
while (guess_value != number){
    printf("
Enter a number between 0 and 100
");
    scanf("%d", &guess_value);      
    number_of_guesses++;
    if (guess_value == number){
        printf("Right !!! You win
");
    }
    else if (guess_value > number){
        printf("
Your guess is too high. Guess again");
    }
    else {printf("
Your guess is too low. Guess again");
    }
}

printf("You guessed %d times !", number_of_guesses);

printf("Do you want to play again? y? n?");
scanf("%c", &answer);
if (answer == 'y'){ 
    goto A; /*return to to beginging*/
}
return 0;   
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think the problem is that you compare guess_value before initialization.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...