Histidine
Histidine

Reputation: 49

rand() gives back higher int than my max c++

So I hope I am not asking something stupid.

I want my program to pause for a random amount of ms going from 2000 to 5999 when a button is clicked so here is are the lines :

void ExpNatDlg::OnBnClickedBack()
{
   int delayRand;
   delayRand = (int)rand() % 6000 + 2000;
   Sleep(delayRand);
}

To check the delays I get, I print them on a file, and I don't know why, I sometimes get delays higher than 7000 ms...

I don't know what I'm missing ! Thanks for your help!

Upvotes: 3

Views: 241

Answers (2)

shuttle87
shuttle87

Reputation: 15934

The problem is that (int)rand() % 6000 will be anywhere up to 5999 so when you add 2000 you will go over the threshold. To get the min and max of 2000 and 6000 you need to have (int)rand() % 4000 + 2000. This is because the random number will be generated in the range 0 to 3999 and then adding 2000 will give the range 2000 to 5999.

If you have c++11 available to you you could write the code like this:

///init for RNG
std::random_device rd;
std::default_random_engine generator;
generator.seed( rd() );

//using the RNG
std::uniform_int_distribution<int> distribution(0,6000);
Sleep(distribution(generator));

The benefits here are that the random numbers will be of a higher quality and the intent of your code is clearer.

Upvotes: 1

gnasher729
gnasher729

Reputation: 52538

That's a simple question of mathematics. rand () % 6000 gives a result from 0 to 5999. Adding 2000 gives a result from 2000 to 7999.

Upvotes: 5

Related Questions