+ 1

why after setting the seed once code outputs three different numbers?

https://code.sololearn.com/cx839w06mx1q/?ref=app

17th May 2023, 6:35 PM
Tomasz Smoleń
Tomasz Smoleń - avatar
4 odpowiedzi
+ 4
Its the same seed, but based in the time. Look Orin Cook’s comment srand(time(0)) int rand_num = rand%10 + 1 for (int i = 0; i < 3; i++){ cout << rand_num << endl; }
17th May 2023, 6:40 PM
Ugulberto Sánchez
Ugulberto Sánchez - avatar
+ 3
That's not actually correct, once the seed is set it's static until you set it again (or the program terminates). The reason it generates 3 different numbers is because that's how pseudorandom number generation works: it'll generate a whole large series of pseudorandom numbers, and it'll eventually repeat but not for a very long time depending on the exact implementation. What does happen, and the reason it's a good idea to use time as your seed, is that if you use the same fixed seed the program will generate the same three numbers each time it runs. By using time as your seed, you can guarantee that the program has a different seed each time it runs.
17th May 2023, 10:03 PM
Orin Cook
Orin Cook - avatar
+ 2
Print time(0) and observe.
17th May 2023, 6:38 PM
Lisa
Lisa - avatar
+ 2
Tomasz Smoleń it outputs different results each time because your seed is based on time. Good if you want a different set of random numbers everytime you run your program. Try srand(0); or any number then try any other number (srand(5)). Then try 0 or that first number again. The results are consistent for a particular seed. Good if you want consistent random values everytime.
18th May 2023, 1:47 AM
Bob_Li
Bob_Li - avatar