Coin Toss

Can anyone explain this????
{
Write a program that simulates coin tossing. For each toss of the coin, the program should print Heads or Tails. Let the program toss the coin 100 times and count the number of times each side of the coin appears. Print the results. The program should call a separate function flip that takes no arguments and returns 0 for tails and 1 for heads. [Note: If the program realistically simulates the coin tossing, then each side of the coin should appear approximately half the time.]
}
Last edited on
It looks like it's explained pretty well. To simulate a coin toss, you just need to generate a random number between 0 and 1. 0 can be heads, and 1 can be tails.

Then just keep track of the results and do the printout like it describes.
Thanks. Do I initialize counter as 0 or coin?
counter should be 0 before you do any tosses.
In fact you will want two counters. One for heads and one for tails.

@disch - instructions specify 'returns 0 for tails and 1 for heads"
Thank you very much :)
I'd probably use the 2 counters in a different way, one to keep track of how many tosses have been performed, and one to keep the result of one outcome (since there's only 2 outcomes it's just one minus the other).

I'd do this rather than using 3 counters, or rather than using a heads and tails counter because I'm a performance freak... I'd rather have one sum at the end to find the tails result rather than one sum on every loop to test the number of flips.

btw if you've not covered it yet then here's basic random number generation:
1
2
3
4
5
6
srand(time(0));
/*Rand must be seeded by some method otherise it'll be
same every time you run program*/
int num = rand() % 2;
/*The function returns a random number using it's special
algorithm, then % 2 makes it a 1 or 0*/
Last edited on
I don't really understand srand(time(0))
rand() returns a psudeo-random number. If you don't call srand() and run your program 100 times, you will get exactly the same random number sequence each time.

srand() is used to "seed" the random number generator so that it returns a different sequence of random numbers each time. time() is used as a seed since it will be different each time you run the program

http://www.cplusplus.com/reference/cstdlib/srand/
Topic archived. No new replies allowed.