0

So I' ve written this piece of code inside a function, that its purpose is to generate a number in the [1-3] range so I can use it in a swich/case statement. The first time the program uses the function I get a random number in [1-3]. When the program uses the function again, it only gives the same number as the first.

srand((int)time(NULL));
    double a;
    int num;

    a = (double)rand() / ((double)RAND_MAX + 1);
    a = a * 3 + 1;
    num = (int)a;
  • 2
    Welcome to Stack Overflow. Please read [the help pages](http://stackoverflow.com/help), take the SO [tour], read [ask], as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Lastly please learn how to create a [mcve] to show us instead of describing parts of the code. – Some programmer dude Apr 06 '20 at 19:48
  • *"its purpose is to generate a number in the [1-3] range so I can use it in a swich/case statement"* So, why are you not using a simple `int num = rand() % 3 + 1;` (once you have moved away the `srand` call)? – Bob__ Apr 06 '20 at 19:59

1 Answers1

2

A pseudo-random number generator will produce the same stream of numbers if seeded with the same seed. Every time srand is called the stream will restart. You're using time which is in seconds. If your function calls are within the same second, they'll get the same stream.

The first part of the solution is to only call srand once at the start of the program. But this is only a partial solution. time alone is a poor seed, and unfortunately, it's in all the tutorials. If the program is run in the same second it will get the same random numbers.

A better seed, on Unix, is to read from /dev/random.

int main() {
    FILE *fp = fopen("/dev/random", "r");
    if( fp == NULL ) {
        perror("Could not open /dev/random");
    }

    unsigned int seed;
    fread(&seed, sizeof(seed), 1, fp);
    srand(seed);

    for( int i = 0; i < 10; i++ ) {
        printf("%d\n", rand());
    }
}

rand is a very poor random number generator. If you need random numbers for security purposes, ones that nobody will be able to guess, use a proper cryptography library.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Schwern
  • 153,029
  • 25
  • 195
  • 336