I'm trying to make a game with dice, and I need to have random numbers in it (to simulate the sides of the die. I know how to make it between 1 and 6). Using
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
int main()
{
srand((unsigned)time(0));
int i;
i = (rand()%6)+1;
cout << i << "\n";
}
doesn't work very well, because when I run the program a few times, here's the output I get:
6
1
1
1
1
1
2
2
2
2
5
2
So I want a command that will generate a different random number each time, not the same one 5 times in a row. Is there a command that will do this?
Using modulo may introduce bias into the random numbers, depending on the random number generator. See this question for more info. Of course, it's perfectly possible to get repeating numbers in a random sequence.
Try some C++11 features for better distribution:
See this question/answer for more info on C++11 random numbers. The above isn't the only way to do this, but is one way.
Can get full
Randomer
class code for generating random numbers from here!If you need random numbers in different parts of the project you can create a separate class
Randomer
to incapsulate all therandom
stuff inside it.Something like that:
Such a class would be handy later on:
You can check this link as an example how i use such
Randomer
class to generate random strings. You can also useRandomer
if you wish.Here is a solution. Create a function that returns the random number and place it outside the main function to make it global. Hope this helps
Here is a simple random generator with approx. equal probability of generating positive and negative values around 0:
The most fundamental problem of your test application is that you call
srand
once and then callrand
one time and exit.The whole point of
srand
function is to initialize the sequence of pseudo-random numbers with a random seed. It means that if you pass the same value tosrand
in two different applications (with the samesrand
/rand
implementation) you will get exactly the same sequence ofrand()
values read after that. But your pseudo-random sequence consists of one element only - your output consists of the first elements of different pseudo-random sequences seeded with time of 1 second precision. So what do you expect to see? When you happen to run application on the same second your result is the same of course (as Martin York already mentioned in a comment to the answer).Actually you should call
srand(seed)
one time and then callrand()
many times and analyze that sequence - it should look random.for random every RUN file