Why does rand() not appear to work | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Why does rand() not appear to work

Ran the code for rand() several times - got the same answer each time. Does not seem very random to me. What is going on? Got the same sequence of numbers with the multiple production variant as well. Not looking good.

3rd Oct 2018, 4:03 AM
Trevor Masters
Trevor Masters - avatar
3 Answers
+ 4
use srand() method to generate true random number example :- #include <iostream> #include <ctime> // for time() #include <cstdlib>// for srand() and rand() using namespace std; int main(){ srand(time(NULL)); cout<<rand(); }
3rd Oct 2018, 4:33 AM
estifanos
estifanos - avatar
+ 4
In your case a single seed is being used, so from that seed the same sequence of pseudorandom numbers is produced. This is a key word too, pseudorandom, because the numbers are generated algorithmically, they just appear random to humans. A seed is used as a parameter to the algorithm so that you get different sequences. This could be provided by the user or taking the system date and time etc.
3rd Oct 2018, 4:47 AM
Dan Walker
Dan Walker - avatar
+ 1
By changing it's range we can change it's random pattern..but Still it's single seeded.
6th Nov 2018, 5:25 AM
J0€|ifteR
J0€|ifteR - avatar