I recently watched a video regarding the Monty Hall problem and found it interesting, so I thought of implementing it to see if the probability is truly 66.6% as predicted.
Here is what I have,
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int repeat = 5000000, i;
int win = 0, lose = 0;
for (i = 1; i <= repeat; i++) {
int winDoor = rand();
winDoor = winDoor % 4;
int firstPick = rand();
firstPick = firstPick % 4;
if (winDoor == firstPick) {
lose++;
} else {
win++;
}
}
printf("%.2f percent win rate\n", ((float)win/(float)repeat)*100.00);
}
However, I seem to be getting a 75% win rate (by switching doors) with the above code. Is there something wrong with my codes? Or is the 66.6% (2/3) a lie?
PS The logic I implemented is, if winning door is first picked, by switching, we lose. If losing door is first picked, by switching, we win. That's how I understand the Monty Hall problem.
EDIT: I actually put %4 because I read that %4 will represent 0-3. I forgot I need 1-3, not 0-3. Question resolved.
The reason is that you're using % 4
instead of % 3
. That simulates 4 doors instead of 3, so the result changes from 2/3
to 3/4
.
You're choosing from 4 doors, not 3. change your %4 to a %3.
include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int repeat = 5000000, i;
int win = 0, lose = 0;
for (i = 1; i <= repeat; i++) {
int winDoor = rand();
winDoor = winDoor % 3;
int firstPick = rand();
firstPick = firstPick % 3;
if (winDoor == firstPick) {
lose++;
} else {
win++;
}
}
printf("%.2f percent win rate\n", ((float)win/(float)repeat)*100.00);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.