//The Monty Hall Problem #include <iostream> #include <cstdlib> // Needed for random numbers using namespace std; // ==================== // main function // ==================== int main() { int i; int numWinsStay = 0; int numWinsSwitch = 0; int prizeDoor, choiceDoor, switchDoor, revealDoor; // Run simulation 10,000 times for (i=0; i<10000; i++) { prizeDoor = rand() % 3; // Pick door with prize behind it choiceDoor = rand() % 3; // Door of contestant‘s pick // Find a door to reveal that is not the prize and not the contestant‘s // choice //两个while始终保持choicedoor,switchdoor,revealdoor为三个不同值:0,1,2。 //prizedoor则为其中一个。 revealDoor = 0; while ((revealDoor == prizeDoor) || (revealDoor == choiceDoor)) { revealDoor++; } // Find a door if the contestant switches switchDoor = 0; while ((switchDoor == choiceDoor) || (switchDoor == revealDoor)) { switchDoor++; } // See if we would have won and increment counters if (choiceDoor == prizeDoor) { numWinsStay++; } else if (switchDoor == prizeDoor) { numWinsSwitch++; } } cout << "If you switch, you will win " << (numWinsSwitch / 100) << "%" << " of the time. " << endl; cout << "If you stay, you will win " << (numWinsStay / 100) << "%" << " of the time. " << endl; return 0; }
The Monty Hall Problem
原文地址:http://9320314.blog.51cto.com/9310314/1545026