随机猜谜游戏卡住了

时间:2014-08-25 07:43:53

标签: c

我正在练习使用SAMS在21天内自学C语言编写C编程的基础知识。

在其中一个类型和运行部分,他们找到了数字(或猜数字)程序,我输入并运行它,但是控制台上的程序卡住了显示以下内容:

获取随机数

我等了一段时间但没有任何反应,即使按下一些按键它也没有做任何事情。

我还不熟悉srand(),time()和rand()例程,因此我不知道如何修复它并使其正常运行。

下面是代码:

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

#define NO 0
#define YES 1

int main (void)
{
    int guess_value = -1;
    int number;
    int nbr_of_guesses;
    int done = NO;


    printf("\nGetting a random number\n");

    /*use the time to seed the random number generator*/

    srand( (unsigned) time(NULL)); 
    number = rand();


    nbr_of_guesses = 0;

    while (done == NO);
    {
        printf("\nPick a number between 0 and %d>", RAND_MAX);
        scanf("%d", &guess_value); /*get a number*/

        nbr_of_guesses++;

        if (number == guess_value)
        {
            done = YES;
        }
        else
            if (number < guess_value)
            {
                printf("\nYou guessed high!");
            }
            else
            {
                printf("\nYou guessed low!");
            }

    }

    printf("\nCongratulations! you guessed right in %d Guesses!", nbr_of_guesses);
    printf("\n\nThe number was %d", number);

    return 0;
}

1 个答案:

答案 0 :(得分:3)

我可以看到2个问题。

while上有一个分号导致程序挂起。

在读取猜测之前,没有什么可以确保输出缓冲区被刷新。

我已发表评论以表明代码更改。

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

#define NO 0
#define YES 1

int main (void)
{
    int guess_value = -1;
    int number;
    int nbr_of_guesses;
    int done = NO;


    printf("\nGetting a random number\n");

    /*use the time to seed the random number generator*/

    srand( (unsigned) time(NULL)); 
    number = rand();


    nbr_of_guesses = 0;

    while (done == NO)   // Removed the ;
    {
        printf("\nPick a number between 0 and %d>", RAND_MAX);
        fflush(stdout);  // stdout is line buffered, and since there is no \n in the printf we need an explicit call to fflush,
        scanf("%d", &guess_value); /*get a number*/

        nbr_of_guesses++;

        if (number == guess_value)
        {
            done = YES;
        }
        else
            if (number < guess_value)
            {
                printf("\nYou guessed high!");
            }
            else
            {
                printf("\nYou guessed low!");
            }

    }

    printf("\nCongratulations! you guessed right in %d Guesses!", nbr_of_guesses);
    printf("\n\nThe number was %d", number);

    return 0;
}