Function help
My homework is to simulate a coin toss. Using the function flip to return the heads and tails count. tails = 0 heads = 1. Anyways I cant figure out why the program is returning this wierd outcome. Heres the codes. Everything is good up to the flip() function but once it return back to main the numbers get all messed up. Anybody know why it is doing that?
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
// Function prototype
unsigned getFlip();
int main()
{
unsigned heads;
unsigned tails;
cout<< "Please enter how many times you'd like to flip the coin"<<endl;
getFlip();
// How many times the coin hit heads and tails
cout<<"You have flipped tails "<<tails<<" times"<<endl;
cout<<"You have flipped heads "<<heads<<" times"<<endl;
//Initializing the time, and the total number of flips.
unsigned total = 0;
total = heads + tails;
time_t rawtime;
time ( &rawtime );
cout<<"The day of "<<ctime (&rawtime)<<"You flipped the coin "<<total;
cout<<" number of times"<<endl;
system("pause");
return 0;
}
unsigned getFlip()
{
unsigned toss;
unsigned tails = 0;
unsigned heads = 0;
srand(time(0));
cin>>toss;
for (unsigned i = 0; i < toss; i ++)
{
if (rand() % 2)
tails ++;
else
heads ++;
}
return heads,tails;
}
[1748 byte] By [
jrice528] at [2007-11-20 11:27:10]

# 3 Re: Function help
You could set the up as global variables, or pass them into GetFlip by reference.
void GetFlip(int& heads, int& tails)
Also, you're declaring variables as unsigned. You should say unsigned what. int, long, short, what?
GCDEF at 2007-11-9 1:27:44 >

# 4 Re: Function help
you can't return more than one variable from a function. If you need more information back (such as two integers as in your example) you need to pass them in to the function by reference or pointer as GCDEF said.
Or, if you want to learn about classes then you can consider enclosing them in a class. eg:
class CoinResult {
public:
int GetHeadCount() { return iHeads; }
int GetTailCount() { return iTails; }
void IncrementTailCount() { iHeads++;}
void IncrementHeadCount() {iTails++; }
private:
int iHeads;
int iTails;
};
You could then make your getFlip function store its results in an object of type CoinResult and then return that object.