The code below is what I have so far. It's supposed to basically mimic a random coin flip where the user enters how many times he/she wants to flip the coin. However, my code doesn't seem to be all that random. If it's heads the first coin flip, then it's heads every time until the end of the program. And if it's tails first, then it's tails every time until the end of the program.
I'm basically confused as to why the program is acting like that, and not 100% random.
#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace std;
void coinToss();
int main()
{
int flips;
cout << "How many times would you like to flip a coin? ";
cin >> flips;
while (flips < 0)
{
cout << "Please enter a positive number of flips: ";
cin >> flips;
}
for (int i = 1; i <= flips; ++i)
{
coinToss();
cout << endl;
}
}
void coinToss()
{
unsigned seed = time(0);
srand(seed);
int toss = 1 + rand() % 2;
if (toss == 1)
cout << "Heads!";
else
cout << "Tails!";
}
You should only be seeding the random number generator (with srand) once in your program. Currently you are doing it every time you call coinToss, which will cause this kind of problem.