简体   繁体   中英

C++ random number 1-9

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.

只是这个:

int iRand = (rand() % 9) + 1;

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.

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).

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.

How about

int iRand = (rand() % 9) + 1;

doh beaten by seconds

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM