[英]Seeding srand() once yet rand() gives almost indentical results everytime
I'm trying to create a random array of random integers for a minesweeper game in C.我正在尝试为 C 中的扫雷游戏创建一个随机整数数组。
I'm trying to get random numbers from 1 to 64.我正在尝试获取从 1 到 64 的随机数。
At the beginning of the main()
function I initialize srand(time(NULL))
.在
main()
function 的开头,我初始化了srand(time(NULL))
。 Later in the program, I use rand()
in a loop to generate 8 random integers.稍后在程序中,我在循环中使用
rand()
生成 8 个随机整数。 In my initial test runs for other features, the numbers were perfectly random but as I ran more tests it started to give out integers 1-7 consistently and one random double-digit integer.在我对其他功能的初始测试运行中,这些数字是完全随机的,但随着我运行更多测试,它开始连续给出整数 1-7 和一个随机的两位数 integer。 Worth mentioning these tests are done on the Clion terminal.
值得一提的是,这些测试是在 Clion 终端上完成的。 Is it a problem just because of where I run the program or something else?
仅仅是因为我运行程序的位置还是其他原因造成的问题?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void eightByEight(int randArr[], int lower, int upper, int size);
int main()
{
int i, randNums[8];
srand(time(NULL));
eightByEight(randNums,1,64,8);
for (i = 0; i < 8; i++)
{
printf("%d ", randNums[i]);
}
return 0;
}
void eightByEight(int randArr[], int lower, int upper, int size)
{
int i,num;
for (i = 0; i < size; i++)
{
num = (rand() % (upper - lower + 1)) + lower;
randArr[i] = num;
}
}
The time
function gives you the current time in seconds since the epoch. time
function 为您提供自纪元以来的当前时间(以秒为单位)。 If you run the program twice in a short period of time, the time
function will return the same value on both runs and you'll therefore get the same sequence of random values.如果您在短时间内运行程序两次,则
time
function 将在两次运行中返回相同的值,因此您将获得相同的随机值序列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.