www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/01/15/22:02:05

From: George Foot <mert0407 AT sable DOT ox DOT ac DOT uk>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: rand() problem
Date: 16 Jan 1998 00:07:47 GMT
Organization: Oxford University, England
Lines: 38
Message-ID: <69m8cj$eiv$2@news.ox.ac.uk>
References: <Pine DOT OSF DOT 3 DOT 96 DOT 980115125749 DOT 12355A-100000 AT duke DOT usask DOT ca>
NNTP-Posting-Host: sable.ox.ac.uk
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

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 -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019