# How to get really random numbers with ‘rand ()’ in C?

Posted on

#### Question :

For school work, I need to create a game, for which I need to generate a random number to make it fair. In one case, as I’ll post below, I need to designate a random number between 0 and 2 to modify in the string:

``````int NUM, AUX;
char PORTAS [0] = {'N', 'N', 'N'};

printf ("Entre com o número de participantes: ");
scanf ("%i", &NUM);

PART JOG [NUM];

for ( AUX = 0 ; AUX < NUM ; AUX++ ){
ent_info (&JOG [AUX], AUX);
}

AUX = rand () %3;
PORTAS [AUX] = 'S';
``````

The problem is that every time, AUX gets the number 2 and I need to generate two more random numbers besides that. How can I get around this problem? Thank you.

Most likely you are not initializing the seed to generate the pseudorandom numbers. As this is just for a school job the most common way to generate random numbers in C should be enough.

You can do something like this:

``````(...)
srand(time(NULL)); //inicializar semente

int NUM, AUX;
char PORTAS [0] = {'N', 'N', 'N'};

printf ("Entre com o número de participantes: ");
scanf ("%i", &NUM);

PART JOG [NUM];

for ( AUX = 0 ; AUX < NUM ; AUX++ ){
ent_info (&JOG [AUX], AUX);
}

AUX = rand () %3;  //Numero aleatório entre 0 e 2
PORTAS [AUX] = 'S';
``````

There are other alternatives / algorithms for generating random numbers. If you need something with “better” quality compared to the stdlib library solution, you can use “Mersenne Twister” for example. It is quite fast and you will easily find an implementation. For example here .