gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

C/C++ > Generating a random number in C?

#139560 - d3x - Fri Sep 07, 2007 2:37 pm

Greetings all :)

I'm working with HAM and I need to generate a random number, it should be between 1 and 3, so the amount of random is not huge, but I'm new at both C and HAM, and have no clue how to generate a random number. Using rand() does not give me what I want, any way to tune that to my need?

#139561 - kusma - Fri Sep 07, 2007 2:38 pm

In what way are the numbers from rand() not pleasing you?

#139563 - d3x - Fri Sep 07, 2007 2:51 pm

Well, the random numbers generated are huge, and in deed random, but I need to limit them to be either 1, 2 or 3

#139566 - Diddl - Fri Sep 07, 2007 3:16 pm

rand() generates a number from 0 to RANDMAX.

either divide it by RANDMAX, multiply it by 3 and add 1

or take a modulo (%) 3 and add 1.


first methode is critical if you use integer values ...

#139568 - kusma - Fri Sep 07, 2007 3:57 pm

Code:
#include <stdlib.h>

int rand_range(int range)
{
   return (int)(rand() * ((float)range / RAND_MAX));
}

#139571 - Cearn - Fri Sep 07, 2007 5:00 pm

There are quite a number of RNG threads already, including pros and cons of specific methods.

From the FAQ: http://forum.gbadev.org/viewtopic.php?t=1431, and then follow the linked threads.