tags:

views:

72

answers:

2

I use this function to create random numbers between 100000000 and 999999999

int irand(int start, int stop) {
  double range = stop - start + 1;
  return start + (int)(range * rand()/(RAND_MAX+1.0));
}

When I use it like this, it's properly working

while(1) {
    DWORD dw = irand(100000000, 999999999);
    printf("dynamic key: %d\n", dw);
    Sleep(100);
}

But when I use this function without the while(1), I always get the same number. What do I need to fix?

+2  A: 

The random number generator must be seeded with some source of entropy for you to see different sequences each time, otherwise an initial seed value of 1 is used by the rand function. In your case, calling srand (time(NULL)); once before the irand function is first called should do the trick. You might find this question useful: why do i always get the same sequence of random numbers with rand() ?

Ani
I know this, but when you add srand(time(NULL)) at the start of function I get strange results as well. It's generating the same numbers in the while loop. Outside the while loop I get numbers that are very similar to each other (122933959, 122933916, 123016357)
Bubblegun
@Bubblegun: Put `srand(time(NULL))` *above* the `while` loop - i.e. make sure it is only called once. Otherwise, it will keep reseeding to the current second, which result in the same `rand()` output until the second changes.
Ani
Ok, the while loop is now working with srand. Now I want to use it outside a loop. There it still generates similar numbers (right now: 140869140, 140979003, 141061401). I can't explain this to me
Bubblegun
Where is the call to `srand`?
Ani
in main:srand(time(NULL)); DWORD dw = irand(100000000, 999999999); printf("dynamic key: %d\n", dw);
Bubblegun
A: 

Not a direct answer to your question, but something you should probably read if you're struggling with random numbers. This recent article by our very own Jon Skeet is a good intro to random numbers and the trubles one might run into: http://csharpindepth.com/Articles/Chapter12/Random.aspx

Jakob