random is not so random

This works but the random number is always the same random number every time I compile it

is there something more random that I could use?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
int length; // range of grid
int height; // range of grid
int randhigh; //random identifier 
int randlong; //random identifier
int randnum; // correlates with the number of connection nodes

cout << "How long do you want your grid? "; //set up length of grid
cin  >> length;

cout << "How tall do you want your grid? "; //set up height of grid
cin  >> height;
cout << endl;

vector<vector<double> > countgrid;

countgrid.resize(height);

for (int i = 0; i < height; ++i)
{
  countgrid[i].resize(length);
}

do{ //find a random point on the grid countgrid
  height++;
  length++;
  randhigh = rand() % height;
  randlong = rand() % length;
  height--;
  length--;
  cout << countgrid[randlong][randhigh];
  /* there is also something wronge with this code right here 
     randnum = countgrid[randlong][randhigh];*/
  cout << "<>" <<randnum<< "<>";
  randhigh++;
  randlong++;
}while (randnum <= 0);
http://cplusplus.com/reference/clibrary/cstdlib/srand/

Of course, the rand() function is really a pseudo-random number generator so if you want different results you have to find a way to reseed the algorithm. Perhaps you could use the system clock to seed the number generated. Each time you run the program, the time will be different.
Add the line
 
srand( static_cast<unsigned>( time( 0 ) ) );


At the beginning of your code
Even so, though, you should be aware that the original premise stands:

rand() is not so random.

It is actually pretty lousy. It works well enough for simple computer games and the like... but if you want a really random number, check out http://www.random.org/

Short of that, your pseudo-random number generator should be better than the standard libc's. I recommend you google around
"c/c++ random number generator"
and
"mersenne twister random number generator"

Hope this helps.
Topic archived. No new replies allowed.