1.11M Members

Coin Toss Program

 
0
 

I am trying to write a program that will flip a coin 100 times and count the number of times it lands on heads as well as the number of times it lands on tails. I have a function, flip, that returns 0 for tails and 1 for heads. When I run the program, the output I get is 2 for heads and 99 for tails. I can't figure out where I went wrong in my code.

#include "stdafx.h"
#include <iostream>
#include <cstdlib>

using std::cout;
using std::rand;

int flip();

int main()
{
int coinToss;
int heads, tails;

heads = 1;
tails = 0;
coinToss = 100;
for (int toss = 0; toss < coinToss; toss++)
{
flip();
if (toss == 1)
heads = heads + 1;
else
tails = tails + 1;
}
cout << "Heads appear " << heads << " times.\n";
cout << "Tails appear " << tails << " times.\n";
return 0;
}

int flip()
{
return rand() % 2;
}

 
0
 

You're adding up to one more than the number of times through the loop because you are initializing heads, which is the number of times you get a heads, to 1 rather than 0 in the beginning with this line:

heads = 1;

You are comparing "toss", the counter of the loop, to 1. This is only going to occur exactly once. You call the "flip" function, but you do nothing with it so its return value is lost. You need to compare the return value from flip to 1, not compare the toss counter value to 1.

 
0
 

Thank you. I made adjustments and the program gave me the output of 48 and 52.

Question Answered as of 6 Years Ago by VernonDozier
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article