Predictability Predictability - 1 year ago 101
C++ Question

How to generate a random number in C++?

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()
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:


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?

Answer Source

The most fundamental problem of your test application is that you call srand once and then call rand 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 to srand in two different applications (with the same srand/rand implementation) you will get exactly the same sequence of rand() 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 Loki Astari already mentioned in a comment to the answer).

Actually you should call srand(seed) one time and then call rand() many times and analyze that sequence - it should look random.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download