problem with rand()

Hey guys,
I just programed the following random number generator:
1
2
3
4
5
6
7
8
9
int randGen(int nMin, int nMax)
{
    int nRandNum;

    srand((unsigned)time(0));
    nRandNum = (rand() % nMax) + nMin;

    return nRandNum;
}srand


it generates a random number, but if I call it repeatedly in a for() loop, every number after the first is the same as the first, an example:


7
7
7
7
7
7


Is this because the loop runs so fast that time(0) in srand((unsigned)time(0)) doesn't change? If so, how can I work around that?

Thanks
Last edited on
Is this because the loop runs so fast that time(0) in srand((unsigned)time(0)) doesn't change?


Yes

If so, how can I work around that?


You should only be calling srand() once when the program starts. You should not be calling it every time you generate a random number. Doing so all but completely destroys the random number generation.
Your function doesn't work correctly, by the way, but I suppose you'll see that once you've fixed it.
There's also no need for the local variable.
Last edited on
thanks guys, that got it; thanks for the heads up about the unnecessary variable as well.
Topic archived. No new replies allowed.