+ 3

What is the use of rand () in c?

It gives same output for all the executions

17th Mar 2019, 11:09 AM
Bhagya Lakshmi
5 Answers
+ 10
Please, Before asking a question on the Q/A, try to 🔍SEARCH. . .  to avoid from posting duplicate threads!   ⇹ Follow community RULES: https://www.sololearn.com/Content-Creation-Guidelines/ https://code.sololearn.com/W26q4WtwSP8W/?ref=app https://code.sololearn.com/WvG0MJq2dQ6y/
17th Mar 2019, 12:54 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 2
Explanation please i can't have any idea
17th Mar 2019, 11:19 AM
Bhagya Lakshmi
+ 2
The rand() function isn't actually providing a "random" number. It uses a seed as Fermi mentioned, and from it, the so called "random" numbers are generated with some logic that shouldn't bother you. So when you use the 'srand(time(0))' you're basically telling the compiler to use the current time (in milliseconds if I'm not mistaking) as a seed. Therefore the chance of generating the same number every time is very slim and it feels like a real random.
17th Mar 2019, 11:28 AM
Martin
Martin - avatar
+ 1
Remember to seed your RNG using srand(). #include <iostream> #include <cstdlib> #include <ctime> int main() { srand(time(0)); std::cout << rand(); }
17th Mar 2019, 11:12 AM
Fermi
Fermi - avatar