I have this problem to write in C++ class \"Write a program that has a function
ID: 3623406 • Letter: I
Question
I have this problem to write in C++ class
"Write a program that has a function prototype before main and an implementation of the function after main. The function to be implemented is a coin toss simulation using the random number generator. The function should return 1 or true 50% of the time and 0 or false 50% of the time. Use srand and the system time to make the program run differently each time. (srand(time(NULL));). Keep track of the number of head and tails for 10, 100, 1000, 10,000, 100,000 and 1,000,000 trials. Output the number of heads and tails and number of each as a percentage of the total. Notice that the more trials the more accurate your simulation becomes."
Here is what i have and it repets on with tosses for each of the toss amounts past this. I'm having a problem with the numbers it is outputting. I know the first flip program should only run 10 times, but when i run the program, some large number is in my print out. Any help or hints of what im doing wrong?
/* Coin Toss Program */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
int flip( ) /* start flip function */
{
int i = rand() % 2 ;
if ( i == 1 ){
return 1;
}
else{
return 0;
}
}/* end flip function */
int main( void )
{
srand(time(NULL));
int side;
int tossTen = 10; /* toss coin ten times */
int tossHundred = 100; /* toss coin one hundred times */
int tossThousand = 1000; /* toss coin one thousand times */
int tossTenThou = 10000; /* toss coin ten thousand times */
int tossHunThou = 100000; /* toss coin one hundred thousand times */
int tossMillion = 1000000; /* toss coin one million times */
int headsTen, headsHundred, headsThousand, headsTenThou, headsHunThou, headsMillion = 0;
int tailsTen, tailsHundred, tailsThousand, tailsTenThou, tailsHunThou, tailsMillion = 0;
for ( int i = 1; i <= tossTen; i++ ) /* start ten toss */
{
if ( flip() == 0 ){
headsTen++;
}
else {
tailsTen++;
}
}
/* break ten toss*/......
this printf continues for the other int's as well. Now i know i need to do more math, but i need this to function properly first.
printf( "In the ten toss heads came up %d percent of the time ", headsTen );
printf( "In the ten toss tails came up %d percent of the time ", tailsTen );
Explanation / Answer
Most of your code looks correct - try moving flip out of the if loop. Try this for the if statement int numb = flip() if (numb == 0) { headTen++; } else { tailsTen++; } I would also add break points to check the code and where the number becomes weird. Make sure you are using the right Head and Tails counters for each function. PM me if you need more help!