Reputation:
I am trying to create a random number / letter using rand() however it just returns the same number / letter every time it is called.
void Location::pick() {
srand(time(NULL));
x = rand() % fieldSize + 1;
int locy = rand() % fieldSize + 1; // rand y
switch (locy) {
case 1: y = 'a'; break;
case 2: y = 'b'; break;
case 3: y = 'c'; break;
case 4: y = 'd'; break;
case 5: y = 'e'; break;
}
}
fieldSize is set to 5. I use srand() at the top. Below is where I call the function.
void Fleet::deployFleet() {
bool newLoc = true;
Location tmp;
for (int i = 0; i < fleetSize; i++) {
tmp.pick();
ships[i].setLocation(tmp);
}
}
fleetSize is set to 5. ships[] is an array of 5 ships. setLocation() just sets the location of the ship to the given parameter.
Upvotes: 0
Views: 263
Reputation: 40897
Pseudo-random generators will generate the same sequence of "random" numbers for the same seed.
You are repeatedly seeding the generator with the time in seconds. You're doing it 5 times very quickly. So the time is always the same for each iteration. Hence you get the first number of said sequence and it'll always be the same.
Upvotes: 2