www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/08/16/06:32:41

From: "John M. Aldrich" <fighteer AT cs DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: random number?
Date: Fri, 15 Aug 1997 22:28:11 +0000
Organization: Two pounds of chaos and a pinch of salt
Lines: 47
Message-ID: <33F4D7FB.74A2@cs.com>
References: <33F3CA35 DOT 29B3 AT erols DOT com>
Reply-To: fighteer AT cs DOT com
NNTP-Posting-Host: ppp108.cs.com
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Matt McFadden wrote:
> 
> How can I make a loop that returns or produces a random integer between
> 0-9 on each pass through the loop?

Example code:

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

int rolldice( int ndice, int nsides )
{
    int i, sum;

    /* random returns 0 to MAXINT; clip it to a range with modulus */

    for ( sum = 0, i = 0; i < ndice; i++ )
        sum += random( ) % nsides + 1;

    return sum;
}

int main( void )
{
    int n, s;

    /* seed random number generator */

    srandom( (int) time( NULL ) );

    printf( "How many dice?  " );
    scanf( "%d", n );
    printf( "How many sides?  " );
    scanf( "%d", s );

    printf( "The result is %d.\n", rolldice( n, s ) );
    return 0;
}

-- 
---------------------------------------------------------------------
|      John M. Aldrich       |"A competent and self-confident person|
|       aka Fighteer I       | is incapable of jealousy in anything.|
|   mailto:fighteer AT cs DOT com   | Jealousy is invariably a symptom of  |
| http://www.cs.com/fighteer | neurotic insecurity."  - Lazarus Long|
---------------------------------------------------------------------

- Raw text -


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