Search code examples
crandomsrand

C: Number Guessing Game


How do I define the number that I want the user to guess in a number guessing game?

There are two sample runs of the program that I need to follow, with the boldface being the user's input:

  1. OK, I am thinking of a number. Try to guess it.
    Your guess? 50
    Too high!
    Your guess? 12
    Too low! Your guess? 112
    Illegal guess. Your guess must be between 1 and 100.
    Try again. Your guess? - 20
    Illegal guess. Your guess must be between 1 and 100.
    Try again. Your guess? 23

    ***CORRECT*****

  2. Want to play again? y

    OK, I am thinking of a number. Try to guess it.
    Your guess? 85
    Too high!
    Your guess? 12
    Too low!
    Your guess? 57

    ***CORRECT*****

I'm having trouble getting my script to output ***CORRECT***** when I/the user enter the number 23 in the 1st run. When I input 50, 12, 112, and -20, I get the correct response, but not with 23. After inputting 23, I get "Too low! Your guess?" (I haven't tried the second run because I need to make sure I can get the 1st run to follow the sample.)

Here is a snippet of what I have:

void guessGame() 
{
int num = 23;
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("Try again. Your guess?\n");
        scanf("%d", &guess);
        count ++;
    }
    else if(guess > num)
    {
        printf("Too high! Your guess?\n");
        scanf("%d", &guess);
        count ++;
    }
    else if(guess < num)
    {
        printf("Too low! Your guess?\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);
}

Much help is appreciated. :)


Solution

  • IN your function you initialize num as -

    int num = 23;
    

    but then you make it store any randomly generated number -

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

    which may not be 23 , it can be anything between 1 to 100. Therefore , it shows output that is not expected .

    If you want num to be 23 then remove then statement with rand() .