Monday, July 27, 2009

C++ Monty Hall problem?

#include%26lt;iostream%26gt;


#include%26lt;cstdlib%26gt;


#include %26lt;time.h%26gt;





using namespace std;





const int NUM_GAMES = 10000;


int prizedoor;


int playerguess;


int revealdoor;


int newguessdoor;


int i;





int play_game_no_switch()


{


prizedoor = rand() % 3;


playerguess = rand() % 3;


for (i=0; i%26lt;3; i++)


return 0;


}


int play_game_switch()


{


prizedoor = rand() % 3;


playerguess = rand() % 3;


for (i=0; i%26lt;3; i++)


{


if((i!=prizedoor) %26amp;%26amp; (i!=playerguess))


{


revealdoor = i;


}


}


for (i=0; i%26lt;3; i++)


{


if ((i!=revealdoor) %26amp;%26amp; (i!=playerguess))


{


newguessdoor = i;


}


}


if (newguessdoor == prizedoor) return 1;


return 0;


}


int main()


{


int numWinsSwitch = 0;


int numWinsNoSwitch = 0;


int i;


srand(time(NULL));


for (i=0; i%26lt;NUM_GAMES; i++)


{


numWinsNoSwitch += play_game_no_switch();


numWinsNoSwitch += play_game_switch();


}


This is the first part of my code, the rest of them is fine, when I run it, the program says I won 0 time and lose 10000 time by switching..

C++ Monty Hall problem?
add return 0; to the end of main()





I'm surprised your play_game_no_switch doesn't give a compile error. You have a for loop that is unclosed, which means all it's doing is this:


for(i=0; i%26lt;3; i++){


return 0;


}


I can't figure out what you were trying to do there. Get rid of it completely. The way it is now, it ALWAYS returns 0. You have to add a check before you return:





if( playerguess == prizedoor ) return 1;


return 0;








I don't know if the random number generation is correct because I barely ever use it, but I'll take your word for it.





In main(), you have this:





numWinsNoSwitch += play_game_no_switch();


numWinsNoSwitch += play_game_switch();





Your using the same variable (numWinsNoSwitch) for both styles of play. You need to use numWinsSwitch for the second one. That's why it's giving you 0 for both. Your 'noSwitch' game always loses because it always returns 0. Then you try to play the 'switch' game, and the variable you store the results in is a different one than you are printing out.





Fix those problems and if it still doesn't work, give more information about what's still wrong.


No comments:

Post a Comment