I am creating a C++ function to flip a coin a user specified number of times. For simulating the flipping of a coin, a random number between 0 and 1 is generated to represent each flip of the coin. If that value is less than or equal to 0.5, then assume that the coin landed on heads for values greater than 0.5 the coin is assumed to have landed on tails. My code runs but the calculations are off. Thanks for the help
void FlipACoin()
{
int x_coord;
int flips;
float heads_p;
float tails_p;
int count;
cout << "Flipping of a fair coin has been selected"
<< endl;
cout << endl;
cout << "How many flips of the coin? " << endl;
cin >> flips;
cout << flips << endl;
while (count <= flips)
x_coord = double(rand())/double(RAND_MAX); // value is 0 to 1
if (x_coord <=.5)
heads_p++;
if (x_coord > .5)
tails_p ++;
cout << string(10,'*') << "Option 2: Flipping a Coin "
<< string(10,'*') << endl;
cout << "For " << flips << "of a fair coin:"
<< endl;
cout << "Heads percentage: " << heads_p <<
endl;
cout << "Tails percentage: " << tails_p <<
endl;
cout << string(50,'*') << endl;
cout << endl;
}
Here are the following error you are making.
1. storing the random value of double type in int which store a whole number
2. also running the loop one time more than the user asked
3. providing double if condition which makes the code slower [Although it's not an issue]
Code:
#include <iostream>
using namespace std;
void FlipACoin()
{
float x_coord;
int flips;
float heads_p;
float tails_p;
int count = 0;
cout << "Flipping of a fair coin has been selected" <<
endl;
cout << endl;
cout << "How many flips of the coin: ";
cin >> flips;
while (count < flips)
{
x_coord = double(rand())/double(RAND_MAX) ; // value is 0 to
1
if(x_coord <= 0.5)
{
heads_p++;
}
else
{
tails_p++;
}
count++;
}
cout << string(10,'*') << "Option 2: Flipping a Coin "
<< string(10,'*') << endl;
cout << "For " << flips << " of a fair coin:"
<< endl;
cout << "Heads percentage: " << heads_p <<
endl;
cout << "Tails percentage: " << tails_p <<
endl;
cout << string(50,'*') << endl;
cout << endl;
}
int main()
{
FlipACoin();
return 0;
}
--------------------------------------------------------------------------------------------------------------------------------------------------
Output:


I am creating a C++ function to flip a coin a user specified number of times....