0

I have a big problem , I do not understand.

I need to generate random numbers from the interval.

I am using code:

unsigned int nahodnyCisloZIntervalu(unsigned int min, unsigned int max) {
    int r;
    const unsigned int range = 1 + max - min;
    const unsigned int buckets = RAND_MAX / range;
    const unsigned int limit = buckets * range;

    do {
        r = rand();
    } while (r >= limit);

    return min + (r / buckets);
}

But every time you start the program generates the same numbers!

How to generate truly random numbers usnig C?

1 Answers1

2

Use the standard rand function. It is normal that rand returns the same sequence each time.

Use the srand function at the beginning of your program in order to initialize the random number generator with a "seed", using for example the current time as seed.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • Thank you for your reply, but this code not working for interval. `srand(time(NULL)); return rand() % 6;` (interval 0-6), if i run in while() i get a same numbers. –  Nov 10 '15 at 08:14
  • 1
    @criagoug You must use `srand(time(NULL))` only _once_ at the beginning of your program. – Jabberwocky Nov 10 '15 at 08:16
  • Oh, ok, now it's working, thank you. –  Nov 10 '15 at 08:17
  • @criagoug also read [this quite comprehensive SO article](http://stackoverflow.com/questions/3159644/using-rand-to-generate-a-random-numbers). – Jabberwocky Nov 10 '15 at 08:18