// return a random number between 0 and limit inclusive.
int rand_lim(int limit) {
int divisor = RAND_MAX/(limit+1);
int retval;
do {
retval = rand() / divisor;
} while (retval > limit);
return retval;
}
// Return a random number between lower and upper inclusive.
int rand_lim(int lower, int upper) {
int range = abs(upper-lower);
return rand_lim(range) + lower;
}
As usual, all the others I've seen in this thread can/will produce at least slightly skewed results.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…