Liczby pseudolosowe. srand(time(NULL))

0

Zauważyłem coś dziwnego i chyba jednak nie rozumiem tego generowania liczb pseudolosowych.

To mam w konstruktorze.

srand(time(NULL));
body.setPosition(sf::Vector2f(rand() % 800, rand() % 600));
int i = rand() % 800;
std::cout << i << std::endl;

Gdy tworzę obiekty to "i" cały czas jest takie same, jak to możliwe?
Jeżeli jednak srand(time(NULL)); podrzucę do maina a wywalę z konstruktora to jest normalnie czyli "i" się różnią.

2

srand powinien być wywołany raz przed pierwszym wywołaniem rand najlepiej. Czyli np. jako pierwsza instrukcja w funkcji main.

http://en.cppreference.com/w/cpp/numeric/random/srand

Generally speaking, the pseudo-random number generator should only be seeded once, before any calls to rand(), at the start of the program. It should not be repeatedly seeded, or reseeded every time you wish to generate a new batch of pseudo-random numbers.

Standard practice is to use the result of a call to time(0) as the seed. However, time() returns a time_t value, and time_t is not guaranteed to be an integral type. In practice, though, every major implementation defines time_t to be an integral type, and this is also what POSIX requires.

1 użytkowników online, w tym zalogowanych: 0, gości: 1