Reputation: 33
I'm trying to make a coin flipper in c++. The point of it is to have the coin "flip" 100 times, and display the amount of times it was heads or tails.
For example: "The coin has been flipped 100 times. Heads = 68 Tails = 32
Here's my code so far:
#include <iostream>
#include <random>
int main()
{
using namespace std;
random_device rd;
default_random_engine random(rd());
uniform_int_distribution<int> uniform_dist(1, 2);
int coin;
int heads = 0;
int tails = 0;
coin = uniform_dist(random);
cout << "I will flip this coin 100 times.";
cout << "I will then print the results.";
while (coin != 100)
How can I "flip" the coin 100 times and how would I go about making a loop for the coin?
Upvotes: 0
Views: 1781
Reputation: 206567
I am not sure why a loop is hard for you but this should work.
for ( int count = 0; count != 100; ++count )
{
int coin = uniform_dist(random);
if ( coin == 1 )
{
++heads;
}
else
{
++tails;
}
}
Upvotes: 0
Reputation: 501
There is no need for a loop. What you want is a random number drawn from a binomial distribution:
std::binomial_distribution<int> distribution(100,0.5);
int heads = distribution(random);
int tails = 100 - heads;
See http://www.cplusplus.com/reference/random/binomial_distribution/ and http://en.wikipedia.org/wiki/Binomial_distribution for more information.
Upvotes: 2