Monty Hall程序C ++

时间:2018-09-20 20:45:31

标签: c++

对于我的编程课程,我们正在制作一个模拟Monty Hall问题的程序,但每次在“露出”错误的门后(而不是用户选择)每次都打开门。切换时的百分比应该在66%左右,但是我的程序不断返回拆分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;

}

1 个答案:

答案 0 :(得分:1)

主要问题是elimNum = getRandom(1, 3, winningNum);仅被检查为不等于winningNum,而它也应不等于guessed数。这将使结果达到预期的66%:

elimNum = getRandom(1, 3, winningNum);
while (elimNum == guess) {
     elimNum = getRandom(1, 3, winningNum);
}