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.
Random number generator returning the same value (C++) [duplicate]
-
15-10-2022 - |
문제
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
해결책
제휴하지 않습니다 StackOverflow