hi,
Im trying to create a vector of random integers in C++. Im trying to seed the rand()
function w/ the time that the system have been up. but it just gives me a vector of same numbers. running again gives a different set of same numbers. Can anyone tell my how to seed the the rand function correctly
here's my code
#################
#include "iostream"
#include "vector"
#include "time.h"
using namespace std;
int GiveRandInt(int N); // returns a random integer from 0 to N-1
int main()
{
int NumElements = 10;
int MaxElementSize = 100;
vector<int> Selection(NumElements);
for(unsigned int i = 0; i <= Selection.size() - 1; i++)
{
Selection[i] = GiveRandInt( MaxElementSize );
cout << "element " << i << ": " << Selection[i] <<endl;
}
return 0;
}
int GiveRandInt(int N)
{
srand(time(NULL)); // Seed our random numbers w/ time
//srand(GetTickCount()); // I saw a place use this but it doesn't work here. Anyone know if I need some special header for this to work?
int RandNum = rand() % N;
return RandNum;
}
#################
The reason you are getting the same number every time is that you are reseeding it every time you want to get a random number. You only need to seed it once.
Put this line at the beginning of main() (and remove it from GiveRandInt()):
BTW, the way to get the clock ticks since program start is "clock()" and that is included in <ctime> (the c++ name for <time.h>Code:srand(time(NULL));. If you want to use clock ticks along with the time use this line instead:
Code:srand(time(NULL) + clock());
Bookmarks