Mail Archives: djgpp/1997/08/16/06:32:41
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 -