Search code examples
cloopsrandomsrand

Using rand() and srand(time(NULL)) right after doesn't generate a new random number


for (x = 1; x < 10; x++)
{
    (armoPtr + x) ->def = rand() % b + a;
    if ((armoPtr + x) -> def > b)
        (armoPtr + x) -> def = b;

    srand(time(NULL));

    (armoPtr + x) -> hp = rand() % 5 + 1;
    srand(time(NULL));

    (armoPtr + x) -> valOItem = rand() % (lvlpnts + 1) + max(lvlpnts);
    if ((armoPtr + x) -> valOItem > (lvlpnts + 1))
        (armoPtr + x) -> valOItem = (lvlpnts + 1);
    (armoPtr + x) -> valOItem *= 10;
    srand(time(NULL));
}

Forgive me if it's a pretty mediocre mistake, but shouldn't this loop have new random numbers every time it loops? I'm still in my 2nd term of my first year in Com Sci. Sorry if I suck. Hahahaha


Solution

  • Call srand once before you start to draw random numbers

    srand(time(NULL));
    for (x = 1; x < 10; x++)
    {
    

    and then just make calls top rand() inside the loop:

    srand(time(NULL));
    for (x = 1; x < 10; x++)
    {
        (armoPtr + x) ->def = rand() % b + a;
        if ((armoPtr + x) -> def > b)
            (armoPtr + x) -> def = b;
    
        (armoPtr + x) -> hp = rand() % 5 + 1;
    
        (armoPtr + x) -> valOItem = rand() % (lvlpnts + 1) + max(lvlpnts);
        if ((armoPtr + x) -> valOItem > (lvlpnts + 1))
            (armoPtr + x) -> valOItem = (lvlpnts + 1);
        (armoPtr + x) -> valOItem *= 10;
    }
    

    Feeding srand with time(NULL) more than once in the same second will make you start to draw same numbers from the beginning because time(NULL) granularity is seconds.