rand() | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

rand()

why the rand() function used in a program returns the same numbers again and again? What is the meaning of "random" if they are every time the same ?

1st Jul 2017, 12:11 PM
george georgeson
2 Answers
+ 8
@Jay is correct. All these "random" numbers originate from the same built-in RNG algorithm which requires to be seeded with a different value every time the program runs. By including <ctime>, time(0) returns the system time (time in seconds since 01/01/1970), which is ever-changing and suitable to be used as a seed.
1st Jul 2017, 12:34 PM
Hatsy Rei
Hatsy Rei - avatar
+ 7
you forgot to seed using srand. see the lessons here for a refresher on using rand. srand(time(0)); // use this before you call rand
1st Jul 2017, 12:13 PM
jay
jay - avatar