954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

c++ cointoss help neede plzzzzzzz

i'm supposed to write a program that simulates cointoss. for each toss the program should print heads or tails and it would toss 100 times and counts the number off times each side of the coin appears. it should also call a seperate function 'flip' that takes no argument and returns 0 for tails and 1 for heads. pease help meeee its due today. this is what i have so far:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//#include <stdafx.h>
#include <iostream>
#include <cstdlib>

using std::cout;
using std::rand;

int flip();

int main(void)
{
    
	int heads = 1;
	int tails = 0;
	int coinToss = 100;
	int face;
	
    for (int toss = 0; toss < coinToss; toss++)
    {
	    flip();
        if (toss == 1)
		
			heads++;
		
		else
		
			tails++;
		
     }
	printf("%s%5s\n", "face", " heads or tails");
	printf(" heads%5d\n",   heads);
	printf(" tails%5d\n",   tails);
	
	
    int flip()
    {
      return rand() % 2;
    
	}
}
kele1
Newbie Poster
13 posts since Sep 2009
Reputation Points: 10
Solved Threads: 0
 

Great, you've got some code, and what exactly is your question?

tux4life
Nearly a Posting Maven
2,350 posts since Feb 2009
Reputation Points: 2,134
Solved Threads: 243
 

i keep getting errors when i execute it and i don't get what i want. also it doesn't call the flip function that gives me 0 for tail and 1 for heads. i need to know if the code is correct.

kele1
Newbie Poster
13 posts since Sep 2009
Reputation Points: 10
Solved Threads: 0
 

You have forgotten to use the return value of flip(). If you did this
if (flip()==1) . I think you would be a lot better than looking at your loop count varible.

If really helps lots to run you code on paper, with a list of variables when the code is small and you are beginning. They you would see why you only get one head.

It also helps to printout the results every turn.

StuXYZ
Practically a Master Poster
680 posts since Nov 2008
Reputation Points: 760
Solved Threads: 138
 

First seed your rand function.

srand(time(0));


The this code :

for (int toss = 0; toss < coinToss; toss++)
    {
	    flip();
        if (toss == 1)
 
			heads++;
 
		else
 
			tails++;
 
     }


is wrong.

You need to assign the value return to a variable and then use it to compare.

for(int i = 0; i < 100; i++)
{
    int side = flip();
   if(side == 0) tails++;
   else heads++;
}
firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608
 

also you are starting the variable heads at one which will throw off you answer. you should initialize both heads and tails as 0.

NathanOliver
Veteran Poster
1,084 posts since Apr 2009
Reputation Points: 215
Solved Threads: 189
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You