Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Cannot get a result other than "Too High" for a guessing game in c

I have finished my code for a program that allows a user to enter a range of values to guess from, then randomly generates the number, and then allows the user to guess and reports too low, too high, or correct. When I test run the program, I only get outputs of "Too high." and I've tried debugging and looking at my code but I can't see where it went wrong. Any help is much appreciated!

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

int main()
{

    int min, max, number, guess, count = 0;

    printf("Please enter two integers for the range:
");
    scanf("%d %d", &min, &max);

    number = (min + rand()%(max - min + 1));
    printf("I'm thinking of a number between %d and %d.
", min, max);

    printf("Enter your guess:
");
    scanf("%d", &guess);

    while(guess != number)
    {

        if(guess < number)
        {
            count++;
            printf("Too low.
");
            printf("Enter your guess:
");
            scanf("%d", &guess);
        }

        else
        {
            count++;
            printf("Too high.
");
            printf("Enter your guess:
");
            scanf("%d", &guess);
        }
    }

        count++;
        printf("Correct, it took you %d tries to guess my number. ", count);

return 0;
}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Uh oh, you didn't initialize your random number generator!

Add srand(time(NULL)) at the beginning of your program or your random number will always be the same (and it might well be zero).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...