The question was mostly answered in the comments and another answer, but I will collect it in one place.
The C ++ rand() function does not create a truly random sequence of numbers, but a pseudo-random one. This means that it is basically a predefined sequence of numbers that are "random" but fixed somewhere (actually it’s more complicated, but it’s simplification for a better understanding). Think of it as a long list of integers.
Each call to the rand() function prints the current number and moves the pointer to the "current" random "number" to the next.
What the srand() function does is basically set a pointer to some place in the list. If you do not call the srand() function each time you start it or do not call it with a fixed parameter (seed), you will have the same sequence of numbers each time the program starts.
When you set your seed from seconds, if you run your program twice during this second, your seed will be the same - hence, getting the same result.
Try using the following code:
#include <windows.h> // << other code >> for (int i=0; i<50; i++) { time(&seconds); srand(seconds); cout<< seconds<<" "<<rand()<<endl; Sleep(100); }
You will notice that each “seconds” value corresponds to some fixed “first” value for the rand() function.
Darkwanderer
source share