Mail Archives: djgpp/1998/01/15/22:02:05
On Thu, 15 Jan 1998 13:02:57 -0600 in comp.os.msdos.djgpp Geoff
J. Howard <howard AT duke DOT usask DOT ca> wrote:
: I am just new to the djgpp world of C computing and I tried out a
: simple random number program and kept getting the same "random" number
: generated all the time, which is either 0 or no number. Is this a known
: problem? I have included the code below. I am thinking that it could be as
: a result of my computer not having enough RAM, what is the minimum amount
: I should have to run djgpp properly. Thanks all
The problem is that you aren't seeding the random number generator.
You need to call srand(x) to seed rand() or srandom(x) to seed
random(), where x is the random seed. You can get a reasonable seed
from the system clock in most cases by setting x = time (NULL). If
you do that you need to #include <time.h> too. Revised code (untested):
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
int i;
srand (time (NULL)); /* seed the RNG */
for (i=1; i<= 20; i++) {
printf("%10d", 1 + (rand() % 6));
if (i % 5 == 0)
\n");
}
return 0;
}
--
george DOT foot AT merton DOT oxford DOT ac DOT uk
- Raw text -