Simulate coin tossing - C++ Data Type

C++ examples for Data Type:Random

Description

Simulate coin tossing

Demo Code

#include <ctime>
#include <iostream>

int flip(void);

const int NUM_FLIPS = 100;

int main(int argc, const char *argv[]) {
    int heads = 0;
    int tails = 0;

    srand(static_cast<int>(time(0)));

    for (int i = 1; i <= NUM_FLIPS; ++i) {
        std::cout << i << ": ";

        if (flip() == 1) {
            std::cout << "heads" << std::endl;
            heads++;/*from   w ww .  j  a  v  a2  s.c  o  m*/
        } else {
            std::cout << "tails" << std::endl;
            tails++;
        }
    }

    std::cout << "\nHeads: " << heads << "\nTails:" << tails << std::endl;
    return 0;
}
// simulates the flipping of a coin and returns the results
int flip(void) { 
   return 1 + rand() % 2; 
}

Result


Related Tutorials