Is there a function to generate a random int number in C? Or will I have to use a third party library?
The rand()
function in
returns a pseudo-random integer between 0 and RAND_MAX
. You can use srand(unsigned int seed)
to set a seed.
It's common practice to use the %
operator in conjunction with rand()
to get a different range (though bear in mind that this throws off the uniformity somewhat). For example:
/* random int between 0 and 19 */
int r = rand() % 20;
If you really care about uniformity you can do something like this:
/* Returns an integer in the range [0, n).
*
* Uses rand(), and so is affected-by/affects the same seed.
*/
int randint(int n) {
if ((n - 1) == RAND_MAX) {
return rand();
} else {
// Supporting larger values for n would requires an even more
// elaborate implementation that combines multiple calls to rand()
assert (n <= RAND_MAX)
// Chop off all of the values that would cause skew...
int end = RAND_MAX / n; // truncate skew
assert (end > 0);
end *= n;
// ... and ignore results from rand() that fall above that limit.
// (Worst case the loop condition should succeed 50% of the time,
// so we can expect to bail out of this loop pretty quickly.)
int r;
while ((r = rand()) >= end);
return r % n;
}
}