random numbers

Shiping Zhang ping at cubmol.bio.columbia.edu
Wed Jan 3 04:59:08 AEST 1990


In article <397 at lkbpyr.UUCP> jonas at lkbpyr.UUCP (Jonas Heyman) writes:
>Hello,
>
>I want this program below to generate 10 different randomly numbers,
>but it seems to generate the same ten when you execute the c program.
>
>How do I solve this ?

>	while (i<10) {
>	i++;
>	number=rnd();
>	printf("%d\n",number);
>	}
 
>rnd()
>{
>	int i=0;
>	int long now;
>	
>	srand(time(&now)%37);
>	return(rand());
>}

This is because the computer works much much faster than people think it
would.  From the begin to the end of the while loop, the time spent is
not long enough for time() to return a different number. So srand will
have the same seed, which results in rand() returning the same first
number of a list of random numbers. It's very simple to solve this
problem, that is to call srand() only once before the while loop in the
main() domain, then just only call rand() subseqently to get 'random'
numbers.

-ping



More information about the Comp.lang.c mailing list