Hello guys?
I am a noob at C++, here is my problem I have to solve:
Using a loop and rand(), simulate a coin toss 10000 times
Calculate the difference between heads and tails.
Wrap the above two lines in another loop, which loops 1000 times.
Use an accumulator to sum up the differences
Calculate and display the average difference between the number of heads and tails.
The code is not working as expected in terms of the accumulator, the loop seems to work fine.
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <cmath>
usingnamespace std;
int main()
{
int total {};
srand(static_cast<unsignedint>(time(NULL)));
for (int h = 0; h < 1000; h++) // Loop Coin Toss
{
int heads {}, tails {};
for (int i = 0; i < 10000; ++i) // COIN TOSS
if (rand() % 2 == 0)
++heads;
else
++tails;
total += abs(heads - tails);
}
cout << "The average distance between is " << total / 1000.0 << '\n';
}
#include <iostream>
#include <cstdlib> // <--- Added. For "rand" and "srand".
#include <ctime> // <--- Added.
#include <cmath> // <--- Added.
usingnamespace std;
int main()
{
constexprint MAXLOOPS{ 20 }; // <--- Shortened for testing.
constexprint MAXTOSSES{ 10000 };
int total{}; // <--- Best to initialize all variables. In the end "num" has no use. "heads" and "tails" moved.
//srand(time(NULL));
srand(static_cast<unsignedint>(time(nullptr)));
for (int h = 0; h < MAXLOOPS; h++) // Loop Coin Toss
{
int heads{}, tails{};
for (int i = 0; i < MAXTOSSES; i++) // COIN TOSS
{
//int random = rand() % 2;
if (!(rand() % 2))
{
heads++;
}
else
{
tails++;
}
}
cout << abs((heads++ - tails++)) << '\n'; // <--- Is there a reason for adding 1?
//cin >> num; // <--- Does this have a purpose?
total += abs((heads - tails));
}
cout << "The average distance between is " << static_cast<double>(total) / MAXLOOPS << '\n';
cin.get(); // <--- Needs a prompt.
return 0;
}
Line 4: For my IDE, MSVS2017, "cmath" is included through "iostream". DO NOT count on this for every compiler and set of header files. If you think you need it include it.
When you look through the code the constant variables make it much easier to use. They also avoid magic numbers that may not all get changed if you need to revise the program.