Path: utzoo!utgpu!jarvis.csri.toronto.edu!clyde.concordia.ca!uunet!cs.utexas.edu!rutgers!columbia!cubmol!ping From: ping@cubmol.bio.columbia.edu (Shiping Zhang) Newsgroups: comp.lang.c Subject: Re: random numbers Message-ID: <1990Jan2.175908.7488@cubmol.bio.columbia.edu> Date: 2 Jan 90 17:59:08 GMT References: <397@lkbpyr.UUCP> Reply-To: ping@cubmol.bio.columbia.edu (Shiping Zhang) Organization: Dept. of Biology, Columbia Univ., New York, NY Lines: 33 In article <397@lkbpyr.UUCP> jonas@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