www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/04/30/09:32:29

From: "John M. Aldrich" <fighteer AT cs DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Random generator?
Date: Tue, 29 Apr 1997 20:41:31 +0000
Organization: Two pounds of chaos and a pinch of salt
Lines: 37
Message-ID: <33665CFB.C26@cs.com>
References: <2 DOT 2 DOT 32 DOT 19970429193847 DOT 006a0ec4 AT gate72>
Reply-To: fighteer AT cs DOT com
NNTP-Posting-Host: ppp107.cs.com
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Alan Wilson wrote:
> 
> What is the best way to write code that generates random numbers?  What is
> the code to generate Random numbers say from 1-100 or some number in C.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main( void )
{
    int i;

    srandom( (int) time( 0 ) );   /* seed RNG with clock value */

    /* random() returns 0 to RAND_MAX; clip to whatever value you need
*/
    for ( i = 0; i < 100; i++ )
        printf( "%3d\t", random( ) % 100 + 1 );

    printf( "\n" );

    return 0;
}

You can use srand()/rand() instead of srandom()/random(), but rand() is
not as random as random(), although it's slightly faster.  Try saying
that sentence three times fast!  ;)

Look up this stuff in the libc docs for more info.

-- 
---------------------------------------------------------------------
| John M. Aldrich, aka Fighteer I  |     mailto:fighteer AT cs DOT com     |
| Plan:  To find ANYONE willing to |   http://www.cs.com/fighteer   |
| play Descent 2 on DWANGO!        | Tagline: <this space for rent> |
---------------------------------------------------------------------

- Raw text -


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