c++randomctime

Why do I get the same result from rand when In run it in a loop and srand(time(0)) in each iteration?


I'm trying to generate a random int that is either 0 or 1 in C++. Right now, I receive a 0 every time I run this code, and I'm not sure why. What's the problem here?

#include <ctime>
#include <cstdlib>

srand(time(0));
int randomval = rand() % 2;
cout << randomval << endl;

Actually, in my programming, I run this 100 times in a for loop, and I srand with each loop iteration.


Solution

  • It is called bad luck. Try it again.