3

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?

Bubblegun
  • 31
  • 2

2 Answers2

3

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() ?

Community
  • 1
  • 1
Ani
  • 111,048
  • 26
  • 262
  • 307
  • 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 Sep 25 '10 at 10:49
  • 1
    @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 Sep 25 '10 at 10:51
  • 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 Sep 25 '10 at 10:56
  • Where is the call to `srand`? – Ani Sep 25 '10 at 10:59
  • in main:srand(time(NULL)); DWORD dw = irand(100000000, 999999999); printf("dynamic key: %d\n", dw); – Bubblegun Sep 25 '10 at 11:01
1

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
  • 24,154
  • 8
  • 46
  • 57