Reputation: 4949
I need random numbers from 1 to 9 (without 0).
//numbers 0 to 9
int iRand = rand() % 10;
But I need 1 to 9.
Thanks.
Upvotes: 1
Views: 40286
Reputation: 8946
Regardless that the answer is picked, modulo based ranging is biased. You can find that all over the internet. So if you really care about that then you have to do a bit more than that (assume arc4random() return a 4 byte integer):
#define NUMBER 9.0
#define RANDOM() (((int)(arc4random() / (float)0xffffffff * (float)NUMBER) + 1) % (NUMBER + 1))
I leave it to you to figure out the correct syntax since you sound like a quite capable developer.
Upvotes: 0
Reputation: 385405
To initialize the random number generator call srand(time(0));
Then, to set the integer x
to a value between low
(inclusive) and high
(exclusive):
int x = int(floor(rand() / (RAND_MAX + 1.0) * (high-low) + low));
The floor()
is not necessary if high and low are both non-negative.
Using modulus (%
) for random numbers is not advisable, as you don't tend to get much variation in the low-order bits so you'll find a very weak distribution.
Upvotes: 1
Reputation: 504333
Well, you know how to get a random integer in the range [0, x], right? That's:
rand() % (x + 1)
In your case, you've set x to 9, giving you rand() % 10
. So how can you manipulate a range to get to 1-9? Well, since 0 is the minimum value coming out of this random number generator scheme, we know we'll need to add one to have a minimum of one:
rand() % (x + 1) + 1
Now you get the range [1, x + 1]. If that's suppose to be [1, 9], then x must be 8, giving:
rand() % 9 + 1
That's how you should think about these things.
Upvotes: 8
Reputation: 98886
Try:
int iRand = 1 + rand() % 9;
It works by taking a random number from 0 to 8, then adding one to it (though I wrote those operations in the opposite order in the code -- which you do first comes down to personal preference).
Note that %
has higher precedence than +
, so parentheses aren't necessary (but may improve readability).
Upvotes: 1