0

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.

  • 1
    Don't use `rand()`, especially not `rand() % n`. Read more [here](http://www.azillionmonkeys.com/qed/random.html). Use `srand` with time as the parameter instead. – Eli Sadoff Nov 07 '16 at 16:39
  • reopened as the code is a little different. Highly related: http://stackoverflow.com/questions/37701567/calling-a-random-number-generating-member-function-doesnt-produce-entirely-rand – NathanOliver Nov 07 '16 at 16:40
  • Everything about this code is broken. Multiple seedings, using `time(NULL)` as a seed, using `rand()`, using `%` to limit the range of the numbers... I don't even know where to begin. – nwp Nov 07 '16 at 16:41

1 Answers1

2

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.

Edward Strange
  • 40,307
  • 7
  • 73
  • 125