random number from -9 to 9 in C++

后端 未结 5 2112
伪装坚强ぢ
伪装坚强ぢ 2020-12-31 03:50

just wondering, if I have the following code:

int randomNum = rand() % 18 + (-9);

will this create a random number from -9 to 9?

5条回答
  •  长情又很酷
    2020-12-31 04:13

    You are right in that there are 18 counting numbers between -9 and 9 (inclusive).

    But the computer uses integers (the Z set) which includes zero, which makes it 19 numbers.

    Minimum ratio you get from rand() over RAND_MAX is 0, so you need to subtract 9 to get to -9.

    The information below is deprecated. It is not in manpages aymore. I also recommend using modern C++ for this task.

    Also, manpage for the rand function quotes:

    "If you want to generate a random integer between 1 and 10, you should always do it by using high-order bits, as in

    j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));
    

    and never by anything resembling

    j = 1 + (rand() % 10);
    

    (which uses lower-order bits)."

    So in your case this would be:

    int n= -9+ int((2* 9+ 1)* 1.* rand()/ (RAND_MAX+ 1.));
    

提交回复
热议问题