View Full Version : How to specify a range for rand() in c?
04-17-2001, 01:25 PM
that basically my question?
rand() % 10 <-- random number from 0 to 9.
Hope this helps.
04-17-2001, 05:34 PM
Taking this farther than you may want to go:
rand() % 10 - 7 gives one of 10 random numbers from -7 to 2
( rand() % 10 -7 ) / 2.0 gives one of 10 random numbers from -3.5 to 1, etc.
04-17-2001, 05:49 PM
Or even further, if the width of the range, n, is a power of two, you can use the following for example:
r = rand() & (n-1);
[This message has been edited by DFrey (edited 04-17-2001).]
04-18-2001, 01:17 AM
So the most general solution is maybe:
let [k..l] is the desired range (k < l)
then this expression
(l - k)*(double)rand()/(double)(RAND_MAX) + k
will return you not more than RAND_MAX different "random" values in [k..l].
However, when l-k <= RAND_MAX, I suggest you to use one of the above solutions, since this one is several times slower...
RAND_MAX is the standard define for the maximum random value, returned by rand().
Hope this helps
Powered by vBulletin® Version 4.2.0 Copyright © 2013 vBulletin Solutions, Inc. All rights reserved.