//The following function simulates a die roll
int die1()
{
for (int counter = 0; counter < 2; counter++)
{
srand(time(NULL));
for (int i = 0; i <6; i++)
{
cout << rand()% 6+1 << endl;
return rand()%6+1;
}
}
}
> srand(time(NULL));
You should do this exactly once at the start of main().
Calling it multiple times won't make for better random numbers.
Calling it too often (like in a loop) will make it for distinctly non-random numbers.
> return rand()%6+1;
This makes both your loops redundant.
> cout << rand()% 6+1 << endl;
Which will be different to the one you return.
#include <iostream>
#include <random>
int roll_die(int);
int main()
{
std::cout << "A five-sided die: " << roll_die(5) << '\n';
std::cout << "A 100-sided die: " << roll_die(100) << '\n';
}
int roll_die(int pip)
{
// create a C++11 random engine and seed with std::random_device
// static to keep it alive between function calls
static std::default_random_engine rng(std::random_device {} ());
// create a C++11 static uniform distribution
static std::uniform_int_distribution<> dist { };
// generate a random die roll and return the value
return dist(rng, decltype(dist)::param_type { 1, pip });
}
Fayezilla wrote:
this is what I found in the forums
In addition to the problems salem c mentioned, that is a C library routine for a 6-sided die, not 5-sided you originally requested.
#include <iostream>
#include <cstdlib>
#include <ctime>
int roll_die(int);
int main()
{
// seed the C random generator once with the current timebefore using it
std::srand(static_cast<unsigned>(std::time(0)));
std::cout << "A five-sided die: " << roll_die(5) << '\n';
std::cout << "A 100-sided die: " << roll_die(100) << '\n';
}
int roll_die(int pip)
{
// generate a random number
return std::rand() % pip + 1;
}