Mail Archives: djgpp/1997/04/30/09:32:29
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 -