In C, how to pick a random number in an interval?
In C, the rand()
function is used to generate a pseudo-random number between 0 and RAND_MAX
. RAND_MAX
is a macro defined in stdlib.h
. To generate a number in a given range (between min
and max
), we can use one of the following solutions:
Integer :
// Pick a random number between min and max (included)
int x = min + rand() % (max + 1 - min);
Float :
// Pick a random floating point number between min and max (included)
float x = min + (float)rand() / ((float)RAND_MAX/(max-min));
When using these codes, remember to initialize the generator seed with srand()
so as not to generate the same draws at each run. For more details, check this question :
In C, the rand()
function is used to generate a pseudo-random number between 0 and RAND_MAX
. RAND_MAX
is a macro defined in stdlib.h
. To generate a number in a given range (between min
and max
), we can use one of the following solutions:
Integer :
// Pick a random number between min and max (included)
int x = min + rand() % (max + 1 - min);
Float :
// Pick a random floating point number between min and max (included)
float x = min + (float)rand() / ((float)RAND_MAX/(max-min));
When using these codes, remember to initialize the generator seed with srand()
so as not to generate the same draws at each run. For more details, check this question :
In C, the rand()
function is used to generate a pseudo-random number between 0 and RAND_MAX
. RAND_MAX
is a macro defined in stdlib.h
. To generate a number in a given range (between min
and max
), we can use one of the following solutions:
Integer :
// Pick a random number between min and max (included)
int x = min + rand() % (max + 1 - min);
Float :
// Pick a random floating point number between min and max (included)
float x = min + (float)rand() / ((float)RAND_MAX/(max-min));
When using it, remember to initialize the generator seed with srand()
so as not to generate the same draws at each run. For more details, check this question :
In C, the rand()
function is used to generate a pseudo-random number between 0 and RAND_MAX
. RAND_MAX
is a macro defined in stdlib.h
. To generate a number in a given range (between min
and max
), we can use one of the following solutions:
Integer :
// Pick a random number between min and max (included)
int x = min + rand() % (max + 1 - min);
Float :
// Pick a random floating point number between min and max (included)
float x = min + (float)rand() / ((float)RAND_MAX/(max-min));
When using it, remember to initialize the generator seed with srand()
so as not to generate the same draws at each run.
# | ID | Query | URL | Count |
---|---|---|---|---|
0 | 8627 | pick random number at interval | https://en.ans.wiki/6674/in-c-how-to-pick-a-random-number-in-an-interval | 1 |