-1

I noticed that if I used rand() to generate random values inside a loop, it will change the value at each iteration. However, this is not the case between for function invocations even by seeding via srand().

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

void test(){   
    float r;

    srand(time(NULL));
    r =  (double)rand()/(double)RAND_MAX;
    printf(" %6.3f \n",r);
}  
int main(){

     float r;
    //srand(time(NULL));
    for(int i=0;i<5;i++){
        test();
        //r =  (double)rand()/(double)RAND_MAX;
        //printf(" %6.3f \n",r);
    }

}

How can I force rand() to refresh its values in each function call?

Mike
  • 380
  • 4
  • 19
  • 5
    Seed once per program, only. Move `srand` into `main` as one of the first lines (not inside a loop!). I can see from your commented-out line that you intended this at some point. – MicroVirus Nov 18 '15 at 19:08
  • Hmmm I apologize for this silly question. You are right. I should've been more careful – Mike Nov 18 '15 at 19:09
  • @MicroVirus you should add an answer with that, it will likely help others that try to use `rand()` – Cristik Nov 18 '15 at 19:11
  • The most important reason though is that in debug mode the (VC2008) compiler wants the randomizer to be deterministic and thus always seeds it with he same value, even when calling `time()` (otherwise here would have been different outcomes, even when calling `srand` multiple times). – Paul Ogilvie Nov 18 '15 at 19:11
  • @Cristik Sure, done. – MicroVirus Nov 18 '15 at 19:12
  • 1
    @PaulOgilvie That's not true. It's just that the loop only runs 5 times and the `time()` function doesn't have the resolution to change within such a minuscule amount of time. – MicroVirus Nov 18 '15 at 19:14
  • Here's a more detailed answer: [srand() — why call it only once?](https://stackoverflow.com/questions/5574914/srandtimenull-doesnt-change-seed-value-quick-enough) – narendra-choudhary Nov 18 '15 at 19:14

1 Answers1

1

Seed once per program, only. Move srand into main as one of the first lines (not inside a loop!). I can see from your commented-out line that you intended this at some point.

MicroVirus
  • 5,324
  • 2
  • 28
  • 53