Question
Write a C++ program that will simulate a coin toss. First, write this program to try out the rand function (remember to#include ) for (
Write a C++ program that will simulate a coin toss.
First, write this program to try out the rand function (remember to#include
for (int i = 0; i < 10, ++i) { int random_number = rand(); cout << random_number << endl; }
Run the program a few times. What do you observe?
To prevent this repetition of the same sequence of random numbers whenever the program is run, we have to "prime" the rand function with a different "seed" each time:
// place this statement just ONCE at the start of your main: srand(time(0));
When submitting on hypergrade do not use srand, only use rand();
Now run the program a few times, as you did before: what do you observe this time?
Now simulate the coin toss:for this, you will need to restrict your random numbers to justtwo values: Let's use 0 to represent heads, and 1 for tails.
What integer operator will you use - i.e. turn the huge range of the "raw" rand function into a range of just 2 possible values?
Use a while loop to ask the user if they wish to toss the coin, and keep on doing so while the user answers "yes"; for each toss output the word "heads" or "tails" according to the random value obtained.
User input has beenbolded and underlinedfor emphasis:
Toss the coin?yes
heads
Toss the coin?yes
heads
Toss the coin?yes
tails
Toss the coin?yes
heads
Toss the coin?no
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started