user63898 user63898 - 4 months ago 13
C Question

C random number generator generate sometimes the same numbers

i have strange behavior in which i try to generate random numbers
and they sometimes totally the same ,
or there is problem if they created on the same time?
using VC 2012

for (int i = array_size; i < (array_size); i++)
{

srand((unsigned int)time(NULL));
int rw = rand() % 960 + (20); //returns a pseudo-random integer between x resolution size 0 -> width
int rh = rand() % 640 + (20); //returns a pseudo-random integer between x resolution size 0 -> height
lwsl_notice("c:%d width %d height %d\n",c, rw, rh);
c++;
}


The output is :

[2016/06/30 09:39:09:7274] NOTICE: c:0 width 606 height 567
[2016/06/30 09:39:09:7274] NOTICE: c:1 width 606 height 567
[2016/06/30 09:39:09:7274] NOTICE: c:2 width 606 height 567
[2016/06/30 09:39:09:7274] NOTICE: c:3 width 606 height 567

Answer

Your loop is so fast that time(NULL) always have the same value. This means that your generator always starts from the same seed, so it will always generate the exact same values.

srand should be called once and only once in your program (outside the for loop). Commonly, people call it once from themain function.