-1

To generate random numbers between 0 and 1, I have written the following but of code:

 double random_0_to_1(){
    srand (time(NULL));
    random();
    return (double)random() / (double)RAND_MAX;
}

int main(){

    for(int i = 0 ; i < 10 ; i++){
        double temp = random_0_to_1();
        printf("%f\n", temp);
    }
    return 0;
}

The result that is generated however is always the same, no matter how many times I call it. The same numbers are always generated. I have tried a lot of different ways, but can't seem to find anything that works. Is there a way to generate random numbers that are different every time I call random_0_to_1?

Vincent VD
  • 51
  • 4

1 Answers1

1

There are three bugs in your code:

  1. You're calling srand more than once. You should only call srand once, at the beginning of main.
  2. You're initializing the RNG with srand, but then you're calling random, which uses a different, unrelated RNG. You should be calling rand.
  3. You didn't include the necessary headers, <stdlib.h>, <time.h> and <stdio.h>, so your code has undefined behavior.
melpomene
  • 84,125
  • 8
  • 85
  • 148
  • I see, in the meantime I tried to include the 'srand' in my 'main', but it didn't work. I had read somewhere that calling 'random' would produce a better result, but that doesn't seem to be the case, since I now get different numbers every time I call my main. Thank you! – Vincent VD Nov 18 '18 at 14:19
  • 1
    @VincentVD If you want to use `random`, you need to seed with `srandom`. – melpomene Nov 18 '18 at 14:20