+ 3
If it print a random no. Then how can we get same no. Each time?
4 ответов
+ 12
the rand() function is based on a complex algorithm, in which each iteration returns a number that is seemingly unrelated to the last one. However, it's still an algorithm, and every time we run it, will run the same algorithm, thus giving us the same sequence than last time.
Now, that doesn't mean it will always output the same number. The sequence is the one that is constant.
Actually, no computer can generate a truly TRULY random number, as randomness depends on probability, while computes are deterministic ( meaning that for the same input, it will return the same output).
The difference between rand() and srand() is that the first one doesn't depend on any variable, so is a constant sequence. The second one will take a number as an input (called seed) and will use it inside an algorithm to generate a seemingly random sequence. Again, this is pseudo randomness, since if you give it the same seed, it will return the same sequence.
Hope this makes sense to anyone.
+ 3
rand() is not truly random. Its called psuedo-random.
You can give a seed to it to make different random numbers, with srand.
and to make always different numbers the seed should be different everytime.
and the only thing which is different everytime, is time itself.
that is why we use srand(time(0)).
+ 2
we are getting same each time as the seed is same we should use new seed instead of that. seeds are the ultimate cause of randomness it initiates the difference
+ 1
great answers :)