I am supposed to create a coin toss sim in c++. I have this code; however, I am getting the same output for all 20 tosses meaning I either get heads for all twenty tosses or I get tails for all twenty tosses. I never get any variation as I am supposed to. I feel as if I have done everything correctly except for that one part. Can anyone point me in the right direction?
Code:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
class Coin
{
public:
Coin()
{
toss();
}
void toss()
{
unsigned seed = time(0);
srand(seed);
int num = (rand()%(2));
if (num == 0)
{
sideUp = ("Heads");
}
else
{
sideUp = ("Tails");
}
}
string getSideUp()
{
return sideUp;
}
private:
string sideUp;
};
int main()
{
int totHeads = 0, totTails = 0;
Coin flip;
cout<<"Flip #1: "<<flip.getSideUp()<<endl;
if (flip.getSideUp() == ("Heads"))
{
totHeads += 1;
}
else
{
totTails += 1;
}
for (int x = 2; x <= 20; x++)
{
flip.toss();
cout<<"Flip #"<<x<<": "<<flip.getSideUp()<<endl;
if (flip.getSideUp() == ("Heads"))
{
totHeads += 1;
}
else
{
totTails += 1;
}
}
cout<<"The total amount of heads were: "<<totHeads<<endl;
cout<<"The total amount of tails were: "<<totTails<<endl;
return 0;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…