View Single Post
srand() aberration ???
Old
  (#1)
Pierre-Marie Baty
Roi de France
 
Pierre-Marie Baty's Avatar
 
Status: Offline
Posts: 5,049
Join Date: Nov 2003
Location: 46°43'60N 0°43'0W 0.187A
Default srand() aberration ??? - 14-06-2004

well well, I feel kinda n00b here but something is puzzling me.

If I do
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
void main (void)
{
   srand (time (NULL)); // initialize random seed
 
   // generate a pseudo-random number ranging from 0 to 99
   printf ("%d\n", (int) (100 * (float) rand () / (RAND_MAX + 1)));
}
and I run my application, I get the same number each time I run it.

Now if I do
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
void main (void)
{
   srand (time (NULL)); // initialize random seed
 
   for (i = 0; i < 100; i++)
	  rand (); // call rand a couple times 
 
   // generate a pseudo-random number ranging from 0 to 99
   printf ("%d\n", (int) (100 * (float) rand () / (RAND_MAX + 1)));
}
Now I get a different number each time I run it (which is what I expected initially).

But could someone tell me WHY on Earth I need to call rand() a great number of times before using it really to have a random number ? Or put it differently why is it ALWAYS the same numbers that pop up during the first rand() calls, and this NO MATTER what I put in the seed ?

Any explanation ???



RACC home - Bots-United: beer, babies & bots (especially the latter)
"Learn to think by yourself, else others will do it for you."
  
Reply With Quote