2

I am making a simple example in C with rand() but the function always return the same number despite i am using srand().

This is the code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int generate(int min, int max)
{
    srand(time(NULL));
    return rand() % (max - min + 1) + min;
}

int main()
{
    int i;
    for (i = 0; i < 10; i++)
    {

        printf("Number random %d = %d\n", i, generate(1, 100));
    }

    return 0;
}

Execution :

Number random 0 = 40 Number random 1 = 40 Number random 2 = 40 Number random 3 = 40 Number random 4 = 40 Number random 5 = 40 Number random 6 = 40 Number random 7 = 40 Number random 8 = 40 Number random 9 = 40

LPs
  • 16,045
  • 8
  • 30
  • 61
  • 2
    You shouldn't force a new seed every use. You should use ``srand`` at application start, not every time. BTW, you should really consider using ```` instead of old-school ``rand``. – Chuck Walbourn Feb 15 '17 at 07:52
  • 1
    try init the random numbers one time at the beginning of your main function – flotto Feb 15 '17 at 07:55

2 Answers2

4

It is because you are reseeding it every time, and as your program probably runs very quickly, your seed value (time()) is the same for each call as it's smallest increment is 1 second.

Try moving srand() into main() instead and call it once

Mindaugas
  • 1,707
  • 13
  • 20
1

Repeatedly calling srand ruins the statistical properties of the generator.

Call it no more than once.

(The observed behaviour is caused by time(NULL) returning the same value in every iteration of the loop.)

Bathsheba
  • 231,907
  • 34
  • 361
  • 483