random number from -9 to 9 in C++

后端 未结 5 2070
伪装坚强ぢ
伪装坚强ぢ 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.));
    
    0 讨论(0)
  • 2020-12-31 04:20

    Do not forget the new C++11 pseudo-random functionality, could be an option if your compiler already supports it.

    Pseudo-code:

    std::mt19937 gen(someSeed);
    std::uniform_int_distribution<int> dis(-9, 9);
    int myNumber = dis(gen)
    
    0 讨论(0)
  • 2020-12-31 04:23

    Your code returns number between (0-9 and 17-9) = (-9 and 8).

    For your information

     rand() % N;
    

    returns number between 0 and N-1 :)

    The right code is

    rand() % 19 + (-9);
    
    0 讨论(0)
  • 2020-12-31 04:24

    Anytime you have doubts, you can run a loop that gets 100 million random numbers with your original algorithm, get the lowest and highest values and see what happens.

    0 讨论(0)
  • 2020-12-31 04:26

    No, it won't. You're looking for:

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

    There are 19 distinct integers between -9 and +9 (including both), but rand() % 18 only gives 18 possibilities. This is why you need to use rand() % 19.

    0 讨论(0)
提交回复
热议问题