+ 1
I'm not understanding how srand is playing it's role
2 Antworten
+ 8
to extend the answer Sean gave, try some examples by yourself:
try this code:
int main(){
srand(42);
cout << rand();
}
just run it twice and see the output.
then change 42 to something else and check the output again.
then use time(0) instead and see for yourself
dont forget #include <ctime> and <cstdlib>
+ 2
Random number generators technically aren't random - they use "pseudorandom" numbers. Under ordinary circumstances, a pseudorandom number generator will always generate the same numbers each time you run your program. The way you circumvent that issue is by "seeding" the number generator with another number.
The srand() function does just that. A lot of people use the system time as an argument for srand(), because the time is constantly changing, and thus you always get a different seed.