0

I've been trying to have a random number generated for an array of instances allocated dynamically, but every time I try, each instance is always given the exact same value:

//IN MAIN
Enemy* enemy;
int num;
std::cout << "How many enemies would you like there to be?" << std::endl;
std::cin >> num;
enemy = new Enemy[num];

for (int q = 0; q < num; q++)
{
    enemy[q].setAngle();
}

for (int q = 0; q < num; q++)
{
    std::cout << enemy[q].getAngle() << std::endl;
}

//IN THE ENEMY CLASS
void Enemy::setAngle()
{
    srand(time(NULL));
    angle = rand() % 360 + 1;
}

int Enemy::getAngle()
{
    return angle;
}

The output will always be a number between 1 and 360, but when getAngle() is called, the output is just the same number repeated on multiple lines. Why is this happening? What am I doing wrong, and how can I fix it?

Thanks in advance

  • 1
    Try to not reinitializate the seed every time you get a random number. If you initialize the seed multiple times in a small amount of time you would probably get the same seed, and then the same number – Manu343726 Feb 22 '14 at 13:59
  • I think the resolution of `time` is 1 second, so you likely initialize with the same value every time you call the function (see comment above). – MB-F Feb 22 '14 at 13:59

1 Answers1

3

You are seeding the random number generator every time you call setAngle. If this all happens within a second (which is the resolution of time), it will always be seeded with the same value and therefore start at the same pseudo-random value. Instead, you should call srand only once at the start of your program.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
  • Oh my goodness it worked! Thank you so much! This bug's been itching me for weeks. I was never taught that srand is best declared once. Thank you! – Jacque Marliin Feb 22 '14 at 14:07