Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using rand to generate a random numbers

Tags:

c

gcc 4.4.4 c89

I am using the code below. However, I keep getting the same number:

    size_t i = 0;

    for(i = 0; i < 3; i++) {
        /* Initialize random number */
        srand((unsigned int)time(NULL));
        /* Added random number (simulate seconds) */
        add((rand() % 30) + 1);
    }

I would like to get 0 to 30 returned. However, the last time I ran this I got 17 three times.

Many thanks,

like image 308
ant2009 Avatar asked Jul 01 '10 16:07

ant2009


People also ask

What output would rand () generate?

Explanation : rand() generate random number between the wide range of 0 to RAND_MAX.

Is Excel rand truly random?

However, Excel uses what is called a pseudorandom number generator, in this case, the Mersenne Twister algorithm. What that means is that, technically speaking, the numbers that Excel's RAND functions generate aren't truly random.


1 Answers

You're seeding inside the loop (with the same value because of how quickly the loop will be executed), which causes the random number generated to be the same each time.

You need to move your seed function outside the loop:

/* Initialize random number */
srand((unsigned int)time(NULL));

for(i = 0; i < 3; i++) {
    /* Added random number (simulate seconds) */
    add((rand() % 30) + 1);
}
like image 130
Mark Rushakoff Avatar answered Sep 18 '22 23:09

Mark Rushakoff