According to cppreference, rand():
Returns a pseudo-random integral value between 0 and RAND_MAX (0 and RAND_MAX included).
The value of RAND_MAX
is implementation defined, but may very well be the maximum value that can be represented in an int
. By doubling the value you get from rand()
, the result may overflow into a negative number. This is actually undefined behavior.
I see no reason to double the return value of rand()
. You could correct this quite simply:
int rand_draw = rand() % (draw_count + 1);
This will give you random values between 0 and 8, as you specified.
But in modern C++, using the uniform_int_distribution from the C++ Standard Library is a much better way to go. Here's the example from the linked page, modified to show the range you specified:
#include <random>
#include <iostream>
int main()
{
std::random_device rd; //Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
std::uniform_int_distribution<> distrib(0, 8);
for (int n=0; n<10; ++n)
//Use `distrib` to transform the random unsigned int generated by gen into an int in [0, 8]
std::cout << distrib(gen) << ' ';
std::cout << '\n';
}