English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

/*
4. Write a program that simulates coin tossing. For each toss of the coin, the program should print Heads or Tails.
Let the program toss the coin 100 times and count the number of times each side of the coin appears. Print the results.
The program should call a separate function flip that takes no arguments and return 0 for tails and 1 for heads.
*/

#include
#include
#include



using namespace std;


int main()

{
int heads=0;
int tails=0;
int toss;

srand(time(0));

for (int counter = 1; counter <= 100; counter++)
{
toss = 1 + rand() % 2;


if (toss == 1)
heads = heads + 1;

else
tails = tails + 1;

}


cout <<"number of heads: " < cout <<"number of tails: " <
return 0;
}

2007-04-28 20:56:16 · 2 answers · asked by Anonymous in Computers & Internet Programming & Design

2 answers

you almost have it! i will give you a hint, use this line:
toss = 1 + rand() % 2;
Just make it a function! you know how to make a function dont you?

2007-04-29 00:44:48 · answer #1 · answered by justme 7 · 0 0

I tried to make the program as random as possible.
if you have problem compiling or any error mail me at m_gopi_m@yahoo.co.in
/*
head or tail.
*/

#include
#include
#include

int flip();

void main()
{
int head=0,tail=0,i,n=100;

clrscr();
for(i=0;i {
if(flip()==0)
tail++;
else
head++;
}

cout<<"\n Total number of trials: "< cout<<"\n Total number of heads : "< cout<<"\n Total number of tails : "< getch();
}

int flip()
{
static int i=0;
int mod,j;

if(i==0) randomize();
else if(i%7==0) srand(i);

i++;
mod=rand();
mod%=2;

return(mod);
}

Instead you can display some message like

"Welcome to head or tail. Strike any key to continue."
Then run a while loop and wait for keyboard strokes.
Then get the key. Using the counter in while loop and the key the user entered, create a new key for srand();

eg:
cout<<"\n\n Welcome to head or tail. Strike a key to continue.";
i=0;
while(!kbhit())
i++;

a=getch();

i+=a; // now i becomes the seed for srand.

2007-04-29 11:14:17 · answer #2 · answered by Gopinath M 3 · 0 0

fedest.com, questions and answers