Function Help
Oct 6, 2011 at 10:36pm UTC
Hello, I'm having a little problem with my program. The user prints a number, and the value of that number is the number of times the loop will iterate. Basically its a coin toss program, 1 for heads and 2 for tails. The number is random and should display heads OR tails the number of times we tossed the coin.
This is what I did:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void cointoss();
int main()
{
int num; //number of times the coin is tossed
cout << " How many times will we toss the coin? " ;
cin >> num;
cout << "\n 1 for heads, 2 for tails. " << endl;
for (int count = 1; count <= num; count++)
{
cointoss();
}
return 0;
}
void cointoss()
{
unsigned seed = time(0);
srand(seed);
if (1 + rand() % 2 == 1)
{
cout << " Heads " << endl;
}
else if (1 + rand() % 2 == 2)
{
cout << " Its tails " << endl;
}
}
Oct 6, 2011 at 10:39pm UTC
if I enter 20 for the number of times I toss the coin, I would get either 20 heads, or 20 tails.
Oct 7, 2011 at 12:03am UTC
Move this line:
1 2
unsigned seed = time(0);
srand(seed);
.. to line 11.
The seed only needs to be initialized once.
* edit *
and you can shorten your randomizer from the above line to:
srand(time(0));
Same thing.
Last edited on Oct 7, 2011 at 12:05am UTC
Oct 7, 2011 at 3:57am UTC
@illlojik
You don't really need line 14, since you are printing 'Heads' and 'Tails', not 1 or 2. Anyway, I fixed the program to do what you wanted, except I made the random a 0 or 1, and I kept track of what the results were to print it afterward. Remove the Sleep(800) if you don't want the pausing between tosses. Here's the program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
// Coin Toss.cpp : main project file.
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <windows.h>
using namespace std;
int cointoss();
int main()
{
srand(GetTickCount());
int num = 0; //number of times the coin is tossed
int quarter = 0; //the coin being tossed
int heads = 0; //number of times coin is heads
int tails = 0; //number of times coin is tails
cout << "How many times will we toss the coin? " ;
cin >> num;
for (int count = 1; count <= num; count++)
{
cout << "On toss " << count << " the coin turned up" ;
quarter = cointoss();
if (quarter)
tails++;
else
heads++;
Sleep(800);
}
cout << endl << "After " << num << " tosses, heads came up " << heads << " times and tails, " << tails << "..." << endl;
return 0;
}
int cointoss()
{
int coin = (rand() % 2 );
if ( coin == 0)
{
cout << " Heads." << endl;
return coin;
}
if (coin == 1)
{
cout << " Tails." << endl;
return coin;
}
return - 1;
}
Topic archived. No new replies allowed.