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
377 views
in Technique[技术] by (71.8m points)

C Programming Guessing Game

I need help finishing my program. I can't seem to get the last step, when the user enters 'y' to play another game it should start again. If the user enters 'n' then it should end. Thank you in advance for any help. Below is the code I have so far.

Here is the problem:
Write a C program that plays a number guessing game with the user.

Below is the sample run:

OK, I am thinking of a number. Try to guess it.

Your guess?  50
Too high!
Your guess?  250
Illegal guess. Your guess must be between 1 and 200.
Try again. Your guess? 30
**** CORRECT  ****
Want to play again?  y
Ok, I am thinking of a number. Try to guess it.
Your guess?  58
****  CORRECT  ***
Want to play again? n
Goodbye, It was fun. Play again soon.

Code:

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

int main() {
    int i, number, currentGuess, MAX_GUESS = 5;
    int answer = 'n';
    time_t t;

    srand((unsigned) time(&t));
    number = rand() % 200 + 1;

    printf("Welcome to the game of Guess It! 
I will choose a number between 1 and 200. 
You will try to guess that number.");
    printf("If you guess wrong, I will tell you if you guessed too high or too low. 
You have 5 tries to get the number. 
");
    printf("
OK, I am thinking of a number. Try to guess it. 
");

    for (i = 0; i < MAX_GUESS; i++) {
        printf("
Your guess?");
        scanf("%i", &currentGuess);

        if (currentGuess > 200) {
            printf("Illegal guess. Your guess must be between 1 and 200.
");
            printf("Try again.
 ");
        }
        else if (currentGuess > number) {
            printf("Too high!
");
        }
        else if (currentGuess < number) {
            printf("Too low!
");
        }
        else {
            printf("****CORRECT****
");
            return 0;
        }
    }

    printf("Sorry you have entered the maximum number of tries. 
");
    printf("Want to play again? 
");
    scanf("%i", &answer);

    if(answer == 'n') {
        printf("Goodbye, it was fun. Play again soon.
");
        return 0;
    }
    else if (answer != 'n') {
        printf("Ok, I am thinking of a number. Try to guess it.
");
    }
}
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Here's an idea for you to do this in your code:

char answer = 'y';

do
{
    // ...
    printf( "Want to play again (y/n)? " );
    scanf( " %c", &answer );
    // Mind ^ the space here to discard any
    // previously read newline character

} while ( answer == 'y' );

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

...