C – Using rand to Generate Random Numbers

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,

Best Answer

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);
}
Related Question