0

Why rand() value is fixed after running code once????

Hello coderes!! I wonder that why rand() value’s output is fixed after running code once?? For example, when i run rand() function, assume the output is 41. After that, when i run the function again, the output also is 41. I guessed the output is different but it is wrong..

4th Mar 2019, 12:09 PM
김준석
김준석 - avatar
2 Respostas
+ 11
This is because these numbers are not truly random, but pseudorandom. Repeat calls to rand merely return numbers from some sequence of numbers that appears to be random. Each time we call rand, we get the next number in the sequence. If we want to get a different sequence of numbers for each execution, we need to go through a process of randomizing. Randomizing is “seeding” the random number sequence, so we start in a different place. The function that does this is srand() which takes an integer as the seed: void srand(int seed); void srand(6); It is important to only invoke the srand call ONCE at the beginning of the program. There is no need for repeat calls to seed the random number generator here is an helpful link of this. https://stackoverflow.com/questions/9459035/why-does-rand-yield-the-same-sequence-of-numbers-on-every-run
4th Mar 2019, 12:24 PM
GAWEN STEASY
GAWEN STEASY - avatar
0
Thank u so much your kind teaching!! Thank you~~😆
4th Mar 2019, 3:15 PM
김준석
김준석 - avatar