c - 随机函数卡在一个数字上

标签 c

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


int main (){

int guess, maxGuess = 10; 
int goal = rand()%50+1;

for (int i = 0 ; i<maxGuess;i++){
printf("Enter a guess between 1-50:\n");
scanf("%d",&guess); 

if (guess<goal){
    printf("Too low\n");
}
else if(guess>goal){
printf("Too high\n"); 
}

else if (guess == goal){
printf("Correct! the number was %d\n",goal); 
}

}
//printf("Too many guesses, the number was %d\n",goal);  

return 0; 
}

这是我的猜谜游戏代码,当它运行时它会给我相同的数字,例如编译时它一直给我34,随机数不断生成34。我似乎找不到我做错了什么,也许我的东西在错误的地方,我不确定我注释掉了最后一行,看看它是否有帮助,但没有,但我已经看过了,没有发现任何与我的问题真正相似的东西,所以任何帮助是赞赏!

TIA

最佳答案

您永远不会为随机数生成器播种。

如果在调用 srand 之前调用 rand,则随机数生成器的种子为 1。因此每次都会得到相同的数字。

在程序开始时调用一次srand来为随机数生成器提供种子。

srand(time(NULL));
int goal = rand()%50+1;

关于c - 随机函数卡在一个数字上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53111827/

相关文章:

c++ - 保存图像而不压缩

c - FFmpeg - H264 编码器找不到有效设备并且无法配置编码器

c++ - stdlib fopen 中的缓存如何工作?

c++ - 通过 C++ 编译器构建 C 应用程序

c - 我的 struct typedef 有什么问题导致 "dereferencing pointer to incomplete type?"

c - 在 C 中使用按位运算符查找 x 是否大于 y

c - C 中的 getopt 总是为每个参数返回 1 或 '\001'

c - 脚本只读取文件的偶数行

c - GCD逻辑错误

c - c 中的稀疏矩阵插入