Feb 12, 2016 at 5:31am UTC
So in my class we're supposed to make a program where you make it do a cointoss and display the results like so:
How many times do you want to toss the coin? 101
Heads: 57
Tails: 44
Heads Percentage: 56.4 ********************************************************
Tails Percentage: 43.6 *******************************************
I haven't gotten to the percentages yet because when I run it for some reason it freaks out and does a loop of 0 and 3, I have no idea what kind of monster I created and could use some serious help, thank you.
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
#include <iostream>
#include <iomanip>
#include <ctime>
#include <cstdlib>
using namespace std;
int CoinToss (void )
{
int RandomNumber;
RandomNumber = 1 + rand() % 2;
return RandomNumber;
}
int main()
{
int HowManyTimes = 0;
int RandomNumber = 0;
int Heads, Tails;
string HeadTail = "" ;
cout << "How many times will the coin be tossed? " ;
cin >> HowManyTimes;
//seeding the RNG
srand((time(0)));
for (int i = 1; i <= HowManyTimes; i++)
{
RandomNumber = CoinToss();
if (RandomNumber == 1)
HeadTail = Heads;
else if (RandomNumber==2)
HeadTail = Tails;
cout<<"Tails was tossed " <<Tails<<" times" <<endl;
cout<<"Heads was tossed " <<Heads<<" times" <<endl;
}
return 0;
}
Last edited on Feb 12, 2016 at 5:39am UTC
Feb 12, 2016 at 6:22am UTC
Get rid of the "HeadTail" string, initialize Heads and Tails to zero, and replace lines 30 and 32 with incrementing Heads or Tails. The problem here is that you're doing... honestly, I don't know what you're doing, but it clearly isn't what you want.
Feb 12, 2016 at 6:47am UTC
I believe this is what you wanted?
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
#include <iostream>
#include <iomanip>
#include <ctime>
#include <cstdlib>
using namespace std;
int CoinToss (void )
{
int RandomNumber;
RandomNumber = 1 + rand() % 2;
return RandomNumber;
}
int main()
{
char response;
int HowManyTimes = 0;
int RandomNumber = 0;
float Heads = 0, Tails = 0;
cout << "How many times will the coin be tossed? " ;
cin >> HowManyTimes;
//seeding the RNG
srand((time(NULL)));
for (int i = 1; i <= HowManyTimes; i++)
{
RandomNumber = CoinToss();
if (RandomNumber == 1) {
Heads++;
}
else {
Tails++;
}
}
cout << "Tails was tossed " << Tails << " times" << endl;
cout << "Heads was tossed " << Heads << " times" << endl;
cout << setprecision(2) << fixed;
cout << "Tails %" << ((Tails / HowManyTimes) * 100) << " | " ;
cout << "Head %" << ((Heads / HowManyTimes) * 100);
cin >> response;
return EXIT_SUCCESS;
}
Last edited on Feb 12, 2016 at 6:48am UTC