Wednesday, December 27, 2017

C++ Random Generator: Heads or Tails (rand)

#include <iostream>
#include <iomanip>
#include <cstdlib>  // prototype for srand() and rand()
#include <ctime>    // prototype for function time
using namespace std;

int heads = 0, tails = 0, cointoss;
int flip();

int main()
{
    srand( time(0) );

    for (int counter = 0; counter < 10; counter++)
    {
        for (int counter = 0; counter < 20; counter++)
            flip();

        cout << endl;
    }

    cout << endl;
    cout << "Total number of heads =  " << heads << endl;
    cout << "Total number of tails =  " << tails << endl;

    cointoss = rand() % 2;
/*
    if (cointoss == 1)
    {
      return 0;
      cout << "H ";
    }
    else
    {
      return 1;
      cout << "T ";
    }
*/
    return 0;
}

int flip()
{
    cointoss = rand() % 2;

    if (cointoss == 1)
    {
        heads = heads + 1;
        cout << "H ";
    }
    else
    {
        tails = tails + 1;
        cout << "T ";
    }

    return 0;

}

No comments:

Post a Comment