Random number generator gives consistent results

2.8k Views Asked by At

So the goal of my program is to simulate flipping a coin. I'm trying to use a random number generator to generate the number 1 or 2, 1 for heads, 2 for tails.

However I keep getting Tails as the result, where am I going wrong?

#include <iostream>
#include <cstdlib> // Require for rand()
#include <ctime>   // For time function to produce the random number
using namespace std;

// This program has three functions: main and first.

// Function Prototypes
void coinToss();

int main()
{
  int flips;

   cout << "How many times would you like to flip the coin?\n";
   cin >> flips;    // user input
  if (flips > 0)
  {
     for (int count = 1; count <= flips; count++) // for loop to do action based on user input
    { 
     coinToss();    // Call function coinToss
    }
  }
  else
  {
    cout << "Please re run and enter a number greater than 0\n";
  }
  cout << "\nDone!\n";
  return 0;
}

void coinToss() //retrieve data for function main
{
  unsigned seed = time(0);  // Get the system time.
  srand(seed); // Seed the random number generator
  int RandNum = 0;

    RandNum = 2 + (rand() % 2); // generate random number between 1 and 2

    if (RandNum == 1) 
    {
      cout << "\nHeads"; 
    }
    else if (RandNum == 2)
    {
      cout << "\nTails";
    }
}
1

There are 1 best solutions below

2
On BEST ANSWER

you should move the srand function to the begin of main. if you call this function twice in the same second you will get the same numbers from random()

also you should change

RandNum = 2 + (rand() % 2); 

to

RandNum = 1 + (rand() % 2);

rand() % 2 will result in 0 or 1, so adding 1 will result in 1 or 2