gpt4 book ai didi

c - 随机猜谜游戏卡住了

转载 作者:行者123 更新时间:2023-11-30 18:40:36 25 4
gpt4 key购买 nike

我正在使用《SAMS 自学 C 21 天》一书练习 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;
}

最佳答案

我发现有 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;
}

关于c - 随机猜谜游戏卡住了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25481218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com