www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1996/11/29/20:43:18

From: "John M. Aldrich" <fighteer AT cs DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: random #'s
Date: Fri, 29 Nov 1996 17:47:50 -0800
Organization: Three pounds of chaos and a pinch of salt
Lines: 43
Message-ID: <329F9246.4AEC@cs.com>
References: <329f264b DOT 60430893 AT nntp DOT southeast DOT net>
Reply-To: fighteer AT cs DOT com
NNTP-Posting-Host: ppp103.cs.com
Mime-Version: 1.0
To: murray AT cdrom DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Murray Stokely wrote:
> 
>    Whats the best way to generate a random number from 0 to 500?  I
> tried the x=random(500) (borland way) and i got some huge number.
> After reading up on it I found out that random() always returns a #
> between 0 and MAX_INT_SIZE how do i create a much smaller random #?

random() works differently in Borland and DJGPP.  In fact, you should
have received an error when trying to use random( 500 ), because DJGPP
random() doesn't take any parameters.  Did you remember to #include
<stdlib.h>?  Anyway, here's an example of the correct way to use
random()...

#include <stdio.h>
#include <stdlib.h>	/* for random() */
#include <time.h>	/* for time() */
#include <ctype.h>	/* for tolower() */

int main( void )
{
    int r;

    /* seed RNG with clock value - otherwise random() will always
       return the same sequence */
    srandom( (int) time( 0 ) );

    printf( "Type a 'q' to stop, or press Enter to continue." );

    while ( tolower( getchar( ) ) != 'q' )
    {
        r = random( ) % 501;	   /* 0 to 500 */
        printf( "%d", r );
    }

    return 0;
}

-- 
---------------------------------------------------------------------
| John M. Aldrich, aka Fighteer I |        fighteer AT cs DOT com          |
| Proud owner of what might one   |   http://www.cs.com/fighteer    |
| day be a spectacular MUD...     | Plan: To make Bill Gates suffer |
---------------------------------------------------------------------

- Raw text -


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