Help with my simple coin simulation program Thanks!!

[quote][code]Hello,

I am learning C++ in school and I thought I could make my own program demonstrating object oriented programming.

I am trying to do a simple coin flip simulation that in the end should result to roughly .50 as I want to find the probability of it landing on a head.

I have two files, the main.cpp file and my Coin.h file.

numberOfHeads for some reason is equaling numberOfTosses. I am really close to finishing once I figure this out.

Thank you for any help in resolving my problem.

--------------------------------------------------------------------------------

main.cpp:

#include <iostream>
#include "Coin.h"

using namespace std;

int main()
{
	Coin coin;
	int numberOfTosses = 1000;
	int numberOfHeads = 0;
	for (int i = 0; i < numberOfTosses; i++)
	{
		coin.toss();
		if (coin.isHeads() == true)
		{
			numberOfHeads++
		}
	}
	cout << "Number of Heads is: "<< numberOfHeads << " Number of Tosses is: " << numberOfTosses << endl;
	cout << numberOfHeads / numberOfTosses << endl;
	return 0;
}


--------------------------------------------------------------------------------

Coin.h

#include <iostream>

using namespace std;

class Coin
{
public:

	void toss()
	{
		value = (rand() % 2);
	}

	bool isHeads()
	{
		if (value = 1)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

private:

	int value;

};


Last edited on
in the function isHeads you allways set the value to be 1

if (value = 1)
this assigns 1 to value.

you want a comparison:
if (value == 1)


also, you should put this line of code in main, it initializes the random generator, otherwise you'll allways get the same result:
1
2
3
4
5
6
int main()
{
    srand(time(0));

   //...
}



and you forgot a ; after numberOfHeads++
Last edited on
Thank you!

That solved that problem. A simple mistake.

But a new problem occurred and it is probably just as simple lol.

1
2
cout << "Number of Heads is: "<< numberOfHeads << " Number of Tosses is: " << numberOfTosses << endl;
	cout << "The probability of a head is: " << numberOfHeads / numberOfTosses << endl;


The output is showing 0, when it should be calculating 507/1000 for example.

Thanks!
I fixed it by putting (double) on both numberOfHeads and numberOfTosses. Thanks for all your help though Gamer2015.

:D
you only need to put it to one of those ;)
you're welcome!
Topic archived. No new replies allowed.