Вопрос

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

Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top