Hi, I am working with C++ in Visual Studio. It's my first semester doing anything like this ever. Still, I am embarrassed that I am having trouble with this simple "coin flipping" program. The user tells the program how many times to "flip the coin" & then the program tells the user the results of each flip. You'll see I am randomly generating a 1 or a 2 within the function coinFlip to represent heads or tails. However, the problem is that if the user wants more than one coin flip, the "random" number stays the same for all of them, resulting in all heads or all tails. I am thinking this is an issue with the for loop that I have within the function coinFlip, but I cannot figure out what might be going wrong.
Please help! Thanks! (Code below)
Code:
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
int coinFlip(int);
int main()
{
int times;
//ask the user how many times to flip the coin
cout << "I can flip a coin as many times as you want.\nHow many times should I flip it?\nType the number and press Enter.\n\n";
cin >> times;
//explain what just happened
cout << "\n\nI just flipped a virtual coin " << coinFlip(times) << " times.\n";
return 0;
}
//flip the coin
int coinFlip(int numTimes)
{
//count the number down
for (int count = numTimes; count > 0; count--)
{
unsigned seed = time(0);
double coin;
srand(seed);
coin = 1 + rand() % 2;
//display heads if it's 1
if (coin == 1)
cout << "\nheads";
//display tails if it's 2
else if (coin == 2)
cout << "\ntails";
//just in case
else
cout << "\nERROR";
}
return numTimes;
}