Mail Archives: djgpp/1998/03/24/04:15:42
In article <01bd56dd$5d636c80$0f02000a AT frank DOT mtsu DOT edu DOT frank DOT mtsu DOT edu>,
Nathan Cournia <nac2b AT frank DOT mtsu DOT edu> writes
> How do I produce a random interger number between 0 and n. Right now
>I'm
>using the following code:
>
> return (((int)((double)rand()/(double)RAND_MAX))*n);
>
> Unfortunately this equation always produces the result of 0. What I
>need
>is a function that will act as a (n) sided dice. Thanks for the help.
>
> Nathan
>
>
Off-topic for this newsgroup, but anyway...
1 + (int) ((float) n * rand()/(RAND_MAX + 1.0))
generates pseudo-random numbers between 1 and n.
Don't be tempted to use the simpler
1 + (rand() % n)
as it uses the lower-order bits, and might not be very random. If you
used random() rather than rand(), the latter *might* be OK.
The above is based on the Numerical Recipes in C book.
Leon
--
Leon Heller: leon AT lfheller DOT demon DOT co DOT uk http://www.lfheller.demon.co.uk
Amateur Radio Callsign G1HSM Tel: +44 (0) 118 947 1424
See http://www.lfheller.demon.co.uk/dds.htm for details of my AD9850
DDS system. See " "/diy_dsp.htm for a simple DIY DSP ADSP-2104 system.
- Raw text -