monty5.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/random.h>


int ask_user(void)
{
	unsigned int rn;

	rn = 0;
	if (getrandom(&rn, sizeof(unsigned int), GRND_NONBLOCK) == 1){
		perror("getrandom");
		exit(1);
	}
	rn = rn % 3 + 1;
	printf("rn = %d\n", rn);
	return(rn);
}


void set_prize_door(int *door)
{
	printf("Select door where prize is ");
	if ((*door = ask_user()) == 0)
		exit(1);
}

void contestant_picks_door(int *door)
{
	printf("Select door for contestant ");
	if ((*door = ask_user()) == 0)
		exit(1);
}


int main(void)
{
	int prize_door;
	int door_before_switch;
	int win_switch = 0;
	int win_noswitch = 0;
	int number_games = 0;

	set_prize_door(&prize_door);
	contestant_picks_door(&door_before_switch);
	number_games++;
	if (door_before_switch == prize_door){
		/* for not switching */
		win_noswitch++;
	}
	else{
		/* for switching */
		win_switch++;
	}
	printf("Won %d games where we switched, won %d games where we did not switched\n", win_switch, win_noswitch);



	return(0);
}


UC Davis sigil
Matt Bishop
Office: 2209 Watershed Sciences
Phone: +1 (530) 752-8060
Email: [email protected]
ECS 36A, Programming & Problem Solving
Version of April 2, 2024 at 12:13PM

You can get the raw source code here.

Valid HTML 4.01 Transitional Built with BBEdit Built on a Macintosh