Reputation: 11
For my programming class we are making a program that simulates the Monty Hall problem, but switches the door every time after "revealing" the wrong door instead of the user choosing. The percentage when switching is supposed to be around 66%, but my program keeps returning the split 50-50.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int getRandom(int low, int high, int badNum) {
int random = rand() % high + low;
while (random == badNum) {
random = rand() % high + low;
}
return random;
}
int main() {
int guess = 0;
int winningNum = 0;
int elimNum = 0;
int switchedNum = 0;
int switchCount = 0;
srand ((unsigned)time(NULL));
cout << "Please enter a guess: ";
cin >> guess;
cin.get();
while (guess < 1 || guess > 3) {
cout << "Please enter a valid number: ";
cin >> guess;
cin.get();
}
for (int i = 0; i <= 1000; i++) {
winningNum = getRandom(1, 3, 0);
elimNum = getRandom(1, 3, winningNum);
switchedNum = getRandom(1, 3, elimNum);
while (switchedNum == guess) {
switchedNum = getRandom(1, 3, elimNum);
}
if (switchedNum == winningNum) { switchCount++; }
}
cout << "You won " << switchCount / 10 << "% of the time, and lost " << 100 - (switchCount / 10) << "% of the time.";
cin.get();
return 0;
}
Upvotes: 0
Views: 2277
Reputation: 37579
The primary problem is that elimNum = getRandom(1, 3, winningNum);
, that is only checked not to be equal to the winningNum
while it should also be not equal to guessed
number. This will make result be expected 66%:
elimNum = getRandom(1, 3, winningNum);
while (elimNum == guess) {
elimNum = getRandom(1, 3, winningNum);
}
Upvotes: 1