我要创建一个运行Monty Hall的程序,让它成交10000次并输出以下统计数据:
我做错了什么?提前谢谢。
int iterations;
for (iterations = 0; iterations < 10000; iterations++)
{
int prizeIs = (int) ((Math.random() * 3) + 1);
int compChoice = (int) ((Math.random() * 3) + 1);
int zonkIs = 0;
if ( prizeIs == compChoice )
{
boolean chooseFirstZonk = Math.random() < 0.5; // 50% chance
switch ( prizeIs )
{
case 1: if ( chooseFirstZonk )
{
zonkIs = 2;
}
else
{
zonkIs = 3;
}
break;
case 2: if ( chooseFirstZonk )
{
zonkIs = 1;
}
else
{
zonkIs = 3;
}
break;
case 3: if ( chooseFirstZonk )
{
zonkIs = 1;
}
else
{
zonkIs = 2;
}
break;
}
}
else if (prizeIs == 1 && compChoice == 2)
{
zonkIs = 3;
}
else if (prizeIs == 1 && compChoice == 3 )
{
zonkIs = 2;
}
else if (prizeIs == 2 && compChoice == 1 )
{
zonkIs = 3;
}
else if (prizeIs == 2 && compChoice == 3 )
{
zonkIs = 1;
}
else if (prizeIs == 3 && compChoice == 1 )
{
zonkIs = 2;
}
else if (prizeIs == 3 && compChoice == 2 )
{
zonkIs = 1;
}
//generating a 1 or 2 to decide whether to switch doors or not
int switchDoor = (int) (1 + (Math.random() * 2));
switch ( switchDoor )
{
//not switching doors
case 1:
{
//since we didnt switch
//if compchoice == prize
//then thats considered a win
//for not switching
if (compChoice == prizeIs)
{
noSwitch++;
wins++;
games++;
}
//if we didnt win
//the games will be incremented by 1
//later to use to calculate the losses
else
{
games++;
}
}
break;
//switch door
case 2:
{
//since we did switch
//if compchoice == prize
//then thats considered a loss
//because were switching
//to the door that has a zonk
if (compChoice == prizeIs)
{
games++;
}
//if compchoice != prize
//then thats considered a win
//because were switching from the door
//with a zonk to the door with the prize
else if(compChoice != prizeIs)
{
switches++;
wins++;
games++;
}
}
}
if (iterations == 10000)
{
double percentage = 100.0 * (switches/games);
double noswitchpercentage = 100.0 *(noSwitch/games);
System.out.println( "Switch percentage : " + percentage);
System.out.println( "No Switch percentage : " + noswitchpercentage);
System.out.println( "wins : "+ wins);
System.out.println("losses : " + (games - wins));
break;
}
答案 0 :(得分:0)
当玩家获胜时,你只是递增开关/ noswitch。将开关/ noswitch增量移到if之外,最好是游戏增量超出整个开关块,所以它不会重复。
...或者我可能不太了解这些变量的用途。因为这会让你获得50%的游戏。
如果你真的想知道每个策略的胜利%,你需要存储你使用每个策略的次数,以及使用该策略获胜的次数,这比你当前存储的还要多。然后计算是wins_with_strategy / plays_with_strategy,而不是除以总游戏。