开发者

rand() function in c++

i am not quite sure how this function in c++ works:

int rand_0toN1(int n) {
    return rand() % n;
}

Another tutorial on internet says to get a random number between a range you need to do something different however, with a being first number in range and n is number of terms in range:

int number = a + rand( ) % n;

I have read that it is supposed to return a random number between the value of 0 and n-1, but how does it do that? I understand that % means divide and give the remainder (so 5 % 2 would be 1) but how does that end up giving a number between 0 and n-1? Thanks for help in understanding this. I guess i don't understand what the ran开发者_高级运维d() function returns.


The modulo (remainder) of division by n > 0 is always in the range [0, n); that's a basic property of modular arithmetic.

a + rand() % n does not return a number in the range [0, n) unless a=0; it returns an int in the range [a, n + a).

Note that this trick does not in general return uniformly distributed integers.


rand returns a pseudorandom value bewtween 0 and RAND_MAX, which is usually 32767.

The modulo operator is useful for "wrapping around" values:

0 % 5 == 0
1 % 5 == 1
2 % 5 == 2
3 % 5 == 3
4 % 5 == 4
5 % 5 == 0 // oh dear!
6 % 1 == 1
// etc...

As such, by combining that pseudorandom value with a modulo, you're getting a pseudorandom value that's guaranteed to be between 0 and n - 1 inclusive.


According to your own example, you seems to understand how it works.

rand() just returns an integer pseudorandom number between 0 and RAND_MAX, then you apply the modulo operator to that number. Since the modulo operator returns the remainder of division of one number by another, a number divided by N will always return a number lesser than N.


The rand() function returns an integral value in the interval [0...RAND_MAX]. And the results of x % n will always be in the range [0...n) (provided x >= 0, at least); this is basic math.


Please take a look here :

http://www.cplusplus.com/reference/clibrary/cstdlib/srand/

Usually you "seed" it with the time function. And then use the modulus operator to specify a range.


The c++ rand() function gives you a number from 0 to RAND_MAX (a constant defined in <cstdlib>), which is at least 32767. (from the c++ documentation)

The modulus (%) operator gives the remainder after dividing. When you use it with rand() you are using it to set an upper limit (n) on what the random number can be.

For example, lets say you wanted a number between 0 and 4. Calling rand() will give you an answer between 0 and 32767. rand() % 5, however, will force the remainder to be 0, 1, 2, 3, or 4 depending on the value rand() returned (if rand() returned 10, 10%5 = 0; if it returned 11, 11%5 = 0, etc.).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜