i'm looping a random function to get random numbers from a die. the first number is always way too high. can someone please indicate where i'm going wrong.
6422352
1
2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int die()
{
int result = (rand()% 6+1);
return result;
}
int main()
{
srand(time(NULL));
for(int i=0; i<=2; i++)//position of players!=boardSize(a)
{
int res = die();
cout<<res<<endl;
}
}
#include <iostream>
#include <random> // http://www.cplusplus.com/reference/random/int die();
int main()
{
for (int i { }; i < 3; ++i)
{
std::cout << die() << ' ';
}
std::cout << '\n';
}
int die()
{
// create a prng, using the default imp
// seeded with a deterministic random engine
static std::default_random_engine prng(std::random_device {} ());
// create a distribution to simulate a 6 sided die
static std::uniform_int_distribution<int> dis(1, 6);
// simulate a die throw and return it
return dis(prng);
}
5 1 6
Sure, for really trivial uses like this example using <random> looks more complicated than using the C library. But using the C library in C++ apps is not recommended. Even the C standard recommends not using srand/rand if there are alternatives available.