1

This is my code:

#include<stdio.h>
#include<stdlib.h>
#include <time.h>
int main(){
float m, n;
printf("Enter n, m:");
scanf("%f %f", &n, &m);
int l;
l=m-n;
int i;
for(i=0; i<4; i++){
    srand(time(NULL));
    double r=rand();
    r/=RAND_MAX;
    r*=l;
    r+=n;
    printf("%f ", r);
}
return 0;
}

Why it generates same numbers? and when I write srand(time(NULL));before the loop it generates different numbers! why it is like this? how does this program work?

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
fatisati
  • 23
  • 1
  • 6
  • Have you tried `man srand` or even google? – John3136 Oct 21 '15 at 03:03
  • 2
    `time(NULL)` is likely to give you the same value for every iteration of your loop (since it is seconds granularity). So you are seeding with the same value and resetting the `rand` sequence with each `srand` call. There is no need to continuously call `srand`. – kaylum Oct 21 '15 at 03:07
  • @kaylum You've answered a different question. OP is asking why `srand()` changes the number sequence. – John3136 Oct 21 '15 at 03:14
  • @John3136 I guess I was addressing "Why it generates the same number?". The reason is because `srand` resets the sequence every time it is called. So with the same seed the `rand` sequence will be the same each time. – kaylum Oct 21 '15 at 03:18

2 Answers2

5

srand() seeds the random number sequence.

The srand function uses the argument as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand. If srand is then called with the same seed value, the sequence of pseudo-random numbers shall be repeated. ... C11dr §7.22.2.2 2

And time() is typically the same value - for a second @kaylum

[Edit]

Better to call srand() only once early in the code

int main(void) {
  srand((unsigned) time(NULL));
  ...

or, if you want the same sequence every time, do not call srand() at all - useful for debugging.

int main(void) {
  // If code is not debugging, then seed the random number generator.
  #ifdef NDEBUG
    srand((unsigned) time(NULL));
  #endif
  ...
Community
  • 1
  • 1
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
1

The call to time(NULL) returns the current calendar time (seconds since Jan 1, 1970). So its the same seed you are giving. So, rand gives the same value.

Simply you may use:

 srand (time(NULL)+i);
Chand Priyankara
  • 6,739
  • 2
  • 40
  • 63