Question #5897   Submitted by Answiki on 02/22/2022 at 07:18:59 PM UTC

In C, how to avoid that the random draws are always the same?

Answer   Submitted by Answiki on 02/22/2022 at 07:23:55 PM UTC

In C, the rand() function generates random numbers based on a seed. If this seed is not initialized, the generator will produce the same sequence (i.e. the same numbers) at each execution. The seed can be defined with the srand() function.


The classical solution is to initialize the seed with the current time (which changes constantly):

srand (time(NULL));


The following example displays random numbers:

#include <stdio.h>      /* printf, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */

int main ()
{
	printf ("Premier nombre : %d\n", rand()%100);
	srand (time(NULL));
	printf ("Deuxième nombre : %d\n", rand()%100);
	srand (1);
	printf ("Encore le premier nombre : %d\n", rand()%100);

	return 0;
}




3 events in history
Answer by Answiki on 02/22/2022 at 07:23:55 PM

In C, the rand() function generates random numbers based on a seed. If this seed is not initialized, the generator will produce the same sequence (i.e. the same numbers) at each execution. The seed can be defined with the srand() function.


The classical solution is to initialize the seed with the current time (which changes constantly):

srand (time(NULL));


The following example displays random numbers:

#include <stdio.h>      /* printf, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */

int main ()
{
	printf ("Premier nombre : %d\n", rand()%100);
	srand (time(NULL));
	printf ("Deuxième nombre : %d\n", rand()%100);
	srand (1);
	printf ("Encore le premier nombre : %d\n", rand()%100);

	return 0;
}




Answer by Answiki on 02/22/2022 at 07:22:17 PM

In C, the rand() function generates random numbers based on a seed. If this seed is not initialized, at each execution of the program, the generated numbers are identical. 


The classical solution is to initialize the seed with the current time (which changes constantly):

srand (time(NULL));


The following example displays random numbers:

#include <stdio.h>      /* printf, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */

int main ()
{
	printf ("Premier nombre : %d\n", rand()%100);
	srand (time(NULL));
	printf ("Deuxième nombre : %d\n", rand()%100);
	srand (1);
	printf ("Encore le premier nombre : %d\n", rand()%100);

	return 0;
}




Question by Answiki 02/22/2022 at 07:18:59 PM
In C, how to avoid that the random draws are always the same?
# ID Query URL Count

Icons proudly provided by Friconix.