By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,655 Members | 1,860 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,655 IT Pros & Developers. It's quick & easy.

Problems with srand(time(0)) returning the same value for a coin flip problem

P: 1
I am having problems with the random number generator returning the same number each time for a simple coin flip problem.


#include <iostream>
#include <iomanip>
#include <ctime>
#include <cstdlib>

using namespace std;

int main()
{
srand(time(0));
//initialize tosses
int tosses, count, flip, heads, tails;
heads = 0;
tails = 0;


//promt user for number of tosses
cout << "\nHow many times do you want to toss the coin? ";
cin >> tosses;

//ensure number of tosses is a positive integer
while (tosses <= 0)
{
cout << "\nNumber must be a positive integer. ";
cout << "\nHow many times do you want to toss the coin? ";
cin >> tosses;
}

for (count = 0; count < tosses; count++)
{
flip = rand() % 2;
if (flip = 0)
{
heads++;
}
else
{
tails++;
}
}

cout << "\nHeads: " << heads;
cout << "\nTails: " << tails;

//calculate quotiens
int headsquo, tailsquo;

headsquo = (double) heads / tosses;
tailsquo = (double) tails / tosses;

//display quotients
cout << setiosflags (ios::fixed) << setprecision (1) << "\nHeads Percentage: " << headsquo;
cout << setiosflags (ios::fixed) << setprecision (1) << "\nTails Percentage: " << tailsquo;

return 0;
}
Feb 19 '16 #1
Share this Question
Share on Google+
1 Reply


weaknessforcats
Expert Mod 5K+
P: 9,197
This code:

Expand|Select|Wrap|Line Numbers
  1. for (count = 0; count < tosses; count++)
  2.     {
  3.         flip = rand() % 2;    
  4.         if (flip = 0)     <<<<<<<<<!!!!!!
  5.         {
  6.             heads++;
  7.         }
  8.         else
  9. etc...
  10.  
sets the value of flip to 0. Use == for equality and = for assignment.
Feb 19 '16 #2

Post your reply

Sign in to post your reply or Sign up for a free account.