Write a C program that monitors how long it takes for a gambler to go bankrupt u
ID: 3674305 • Letter: W
Question
Write a C program that monitors how long it takes for a gambler to go bankrupt using the rand() function and RAND_MAX definition that are in the math.h library. Prompt the user for an initial amount in the bank account (money) and the number of simulations they would like to perform. Run_simulation executes as follows: a fair coin is tossed (think about it: write a function to generate a random number between zero and one that determines the outcome of the flip), if the coin is heads then $1 is added to the bank account, otherwise the gambler will lose $1. The simulation exits when the gambler has lost all of his/her money. Average the time until bankruptcy after the specified number of simulations have been reached. Use “srand(0);” after you read in the number of simulations from scanf.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>
void run_simulation(double money, int *t_lost);
void get_coin(bool *coin);
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>
void run_simulation(double money, int *t_lost);
void get_coin(bool *coin);
int main() {
int number_of_simulations;
printf("Enter number of simulations: ");
scanf("%d", &number_of_simulations);
srand(0);
int i;
int total_number_of_trials = 0;
for (i = 0; i < number_of_simulations; ++i) {
double money;
printf("Enter balance in the bank: ");
scanf("%lf", &money);
int number_of_trails = 0;
run_simulation(money, &number_of_trails);
total_number_of_trials += number_of_trails;
}
printf("Average number of trials per simulation: %lf", (total_number_of_trials * 1.0) / number_of_simulations);
}
void get_coin(bool *coin) {
*coin = rand() % 2;
}
void run_simulation(double money, int *t_lost) {
while (money > 0) {
bool coin;
get_coin(&coin);
if (coin) money -= 1;
else money += 1;
*t_lost += 1;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.