0

Hi i wanna generate a random number between 2 values. I have 2 variables. This is the default value: (MIN = MAX = 1)

Later this value can change!

I have use this:

rand()%(max-min)+min;

But i got debug about division for zero. Any ideas?

Edit: With the default value the number generated must be 1.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
user2295277
  • 209
  • 1
  • 4
  • 12

2 Answers2

7

In your initial case (max-min) is 0 and modulus by zero is undefined behavior. From the C++ draft standard section 5.6 Multiplicative operators says:

The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined. [...]

As for generating a random number between min and max you should use the random header and uniform_int_distrubution:

#include <iostream>
#include <random>

int main()
{
    std::random_device rd;

    std::mt19937 e2(rd());
    int min = 1, max = 1 ;

    std::uniform_int_distribution<int> dist(min,max);

    for (int n = 0; n < 10; ++n) {
            std::cout << dist(e2) << ", " ;
    }
    std::cout << std::endl ;
}

If for some reason C++11 is not an option then the C FAQ gives us the proper formula when using rand in the section How can I get random integers in a certain range? which indicates to generate random numbers in the range [M, N] you use the following:

M + rand() / (RAND_MAX / (N - M + 1) + 1)

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
  • I know where is the problem so i would like a solution because i have searched allot and found nothing. Edit: With the default value the number generated must be 1. – user2295277 Jan 02 '14 at 17:46
  • @user2295277 added solution as well, it was not clear from your question that you were aware of the source of the issue, Regardless the explanation is useful for future readers for whom may not see it. – Shafik Yaghmour Jan 02 '14 at 18:14
2

The range [min, max] contains max - min + 1 numbers! So your code should have been like this:

rand() % (max - min + 1) + min;

Don't forget to check the value of RAND_MAX though, your range shouldn't get close to that. In fact, you want it to be much smaller than that to avoid too much bias.

user2345215
  • 637
  • 5
  • 9