In C, how to avoid that the random draws are always the same?
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;
}
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;
}
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;
}
# | ID | Query | URL | Count |
---|