int random(){
double x = ((double) rand() / (RAND_MAX)); // this i tried but only 0
return x;
}
how I generate either 0 or 1 randomly for a tic tac toe player to play
int random(){
double x = ((double) rand() / (RAND_MAX)); // this i tried but only 0
return x;
}
how I generate either 0 or 1 randomly for a tic tac toe player to play
If you have C++11
you can use the new standard <random>
library. In particular the std::bernoulli_distribution distribution gives true
or false
results (default convertible to 1
and 0
respectively).
// returns true or false
bool randomly_true(double p = 0.5)
{
thread_local static std::mt19937 mt{std::random_device{}()};
thread_local static std::bernoulli_distribution d;
return d(mt, std::bernoulli_distribution::param_type{p});
}
int main()
{
for(int i = 0; i < 30; ++i)
std::cout << randomly_true() << '\n';
}
Output: (sample)
0
0
0
1
0
1
1
1
0
1
If you always want 1
or 0
integer values rather than true
or false
bool values you can force the conversion by returning int
from the function:
// returns 1 or 0
int randomly_true(double p = 0.5)
{
thread_local static std::mt19937 mt{std::random_device{}()};
thread_local static std::bernoulli_distribution d;
return d(mt, std::bernoulli_distribution::param_type{p});
}
Note: You should use this library in preference to rand()
as there is no guarantee of quality with rand()
and may be very poorly implemented.