Coin Toss

I've approached a very annoying problem with my code.
The idea behind my assignment is that it'll toss a coin 100 times, 1 = heads, 2 = tails, and count how many heads and tails there are in a million tosses, while calculating the percentage.

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
 #include<ctime>
using namespace std;
int main()
{
	for (int x = 0; x < 1000000; x++)
	{ 
		srand(time(NULL));
		int y = rand()%2+1;
		int z=0, g=0;
		while (y=2)
		{
			
			z++;
		}
		 
		while (y=1)
		{
			
			g++;
		}
	
	}
	float perch = (g/1000000)*100;
	float perct = (z/1000000)*100;
	cout << "Number of heads = " << g << ", percent = " << perch << "%" << endl;
	cout << "Number of tails = " << z << ", percent = " << perct << "%" << endl;
	
	
system("pause");
	return 0;
}


The problem is after debugging, I'm not receiving anything--all I have on the output is a blank.
you are assigning values to y.(by doing y=2 and y=1).you need to check like this: y==2
I just made few changes:
you also need g and z to be of float types or the percentage would be calculated as zero(cause they are int)

#include<ctime>
#include<iostream>
#include<cstdlib>
#include<conio.h>

using namespace std;

int main()
{

float z=0, g=0;
int y;

srand(static_cast<unsigned int>(time(0)));
for (int x = 0; x < 1000000; x++)
{

y = (rand()%2)+1;
if(y==2)
{

z++;
}

if(y==1)
{

g++;
}

}
double perch = (g/1000000)*100;
double perct = (z/1000000)*100;
cout << "Number of heads = " << g << ", percent = " << perch << "%" << endl;
cout << "Number of tails = " << z << ", percent = " << perct << "%" << endl;


getch();
}
Last edited on
You have infinite loop on lines 10 and 16. Change loop statement to conditional statement.
Topic archived. No new replies allowed.