-3

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;
}
Stevey
  • 1
  • 2

3 Answers3

2

Your toss function keeps re-seeding the PRNG. Don't.
Call srand once at the start of your program.

Community
  • 1
  • 1
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
2

You are seeding the random number generator every toss, which is not the way to go. Most of the time, you should seed your PRNG only once per program. In your case, you get the same seed since you are seeding multiple times in a very short amount of time, hence you get the same result after each toss, as the PRNG starts reuses the same seed. Simply remove the lines

unsigned seed = time(0);
srand(seed);

from your toss function and put them as the first lines in main. In fact, you can get rid of the seed variable entirely and just write

srand(time(0));

after int main(){

If you have access to C++11, you should use the new functions and PRNGs from <random>, instead of old C-style rand()/srand() combinations. See e.g. http://en.cppreference.com/w/cpp/numeric/random for some introduction.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
1

The problem is that you're seeding the random generator at the start of the toss() function. The program runs so fast that time(0) is the same on each call, so the random number generator is being reset to the same starting point on each call. Thus, you're getting the same random number each time. You should call srand() just once, before you start calling the toss() function repeatedly.

Michael Laszlo
  • 12,009
  • 2
  • 29
  • 47