Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

C++ coin toss simulator not working

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...