home / study / engineering / computer science / questions and answers / c++ prog
ID: 3687637 • Letter: H
Question
home / study / engineering / computer science / questions and answers / c++ program write a function named binaryflip(int ... Question C++ Program Write a function named BinaryFlip(int N) that simulates the tossing of a coin for N times. When you call the function, it should repeatedly generate N random number in the range of 0 through 1. If the random number is 1, the function should display “Head”. If the random number is 0, the function should display “Tail”. 1. Demonstrate the function in a program that asks the user how many times the coin should be tossed, and then simulates the tossing of the coin that number of times, and prints the outcome each time when the coin is tossed. 2. Print the probability (two digits after decimal point) of getting Head and Tail after each toss. Example Output (aligned): > Enter the number of tosses > 20 > 1 Head 1 P(H) = 1.00 P(T) = 0.00 > 2 Tail 0 P(H) = 0.50 P(T) = 0.50 . . . > 20 Tail 0 P(H) = 0.71 P(T) = 0.29
Explanation / Answer
Please find the required solution:
#include <iostream>
#include <random>
using namespace std;
//method prototype
void BinaryFlip(int N);
//test method in main
int main()
{
int i,n,h,t,temp;
cout<<"enter number of flips:";
cin>>n;
BinaryFlip(n);
return 0;
}
//Required method accepts number of flips as input
void BinaryFlip(int N)
{
//h denotes number of heads
//t denotes number of tails
int i,h=0,t=0;
//loop through N iterations
for(i=0;i<N;i++)
{
if(rand()%2==0)
{//count tails and print it
cout<<"TAIL"<<endl;t++;
}
else
{//count heads and print it
cout<<"HEAD"<<endl;h++;
}
}
//print the result
cout<<"P(T)="<<(double)t/N;
cout<<",P(H)="<<(double)h/N<<endl;
}
Sample output:
enter number of flips:5
HEAD
TAIL
HEAD
HEAD
HEAD
P(T)=0.2,P(H)=0.8
enter number of flips:5
HEAD
TAIL
HEAD
HEAD
HEAD
P(T)=0.2,P(H)=0.8
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.