I want to create a program where the user enters the number of trial, where each trial is tossing a coin 5 time. I then want the program to display the percentage of all 5 tosses being heads in a trail. I am having trouble with the counter++, I want it to count when all 5 tosses are heads.
So here you toss the coin five times. But you don't look at it. You don't change the counter, you don't do anything. You just toss it five times and you only look at the outcome of the last toss. Why?
#include <iostream>
#include <cstdlib>
#include <ctime>
int main() {
std::srand( std::time(nullptr) ) ; // *** seed the random number generator
int num_trials = 0 ;
std::cout << "Enter number of trials: ";
std::cin >> num_trials ;
constint num_tosses_per_trial = 5 ; // 5 tosses per trial
int num_trials_with_all_heads = 0 ;
for( int i = 0 ; i < num_trials ; ++i ) { // for 'num_trials' trials
int num_heads_for_this_trial = 0 ;
for( int j = 0 ; j < num_tosses_per_trial ; ++j ) { // for 'num_tosses_per_trial' tosses
// note: we are relying on the randomness of the least significant bit
// of a low-quality pseudo-random number generator
constbool is_head = std::rand() % 2 == 1 ;
if(is_head) ++num_heads_for_this_trial ;
}
if( num_heads_for_this_trial == num_tosses_per_trial ) ++num_trials_with_all_heads ;
}
if( num_trials > 0 ) {
std::cout << "\nnumber of trials: " << num_trials << "\ntosses per trial: " << num_tosses_per_trial << '\n' ;
constdouble pct_all_heads = num_trials_with_all_heads * 100.0 / num_trials ;
std::cout << "percentage of " << num_tosses_per_trial << " heads in a trial : " << pct_all_heads << "%\n" ;
// quick check : if num_trials is reasonably large, the actual result should be close to
// the computed mathematical expectation for most of the runs of the program.
double expectation = 100.0 ;
for( int i = 0 ; i < num_tosses_per_trial ; ++i ) expectation /= 2.0 ;
std::cout << "mathematical expectation: " << expectation << "%\n" ;
}
}