//代码实现:
private static double startGame(bool type)
{
int Ttime = 10000;//测试次数
int mychoice = 0;
int host = 0;
int win = 0;
Random rand = new Random();
for (int i = 0; i < Ttime; i++)
{
int priceDoor = rand.Next(1, 4);//随机门后有奖品
mychoice = rand.Next(1, 4);//参选者随机选择一个门
host = hostchoice(mychoice, priceDoor); //主持人选择一个门(不能为参选者选择的门,且门后没奖品)
if (type)
{
if (mychoice == priceDoor){win++;}
}
if (!type)
{
if (changeChoice(mychoice, host) == priceDoor){win++;}
}
}
return (double)win * 100 / Ttime;
}
private static int hostchoice(int playerChoice, int price)//主持人选择
{
Random rand = new Random();
int opendoor = 0;
List<int> list = new List<int>();
for (int i = 1; i < 4; i++)
{
if (i != playerChoice && i != price)//在奖品与选手选择的之外的门
{
list.Add(i);
}
}
if (list.Count == 1)//选手没选中的情况
{
return list[0];
}
if (list.Count > 1)//选手选择中的情况
{
return list[rand.Next(1, list.Count)];
}
return opendoor;
}
private static int changeChoice(int mychoice, int opendoor)//改变选择
{
int door = 0;
for (int i = 1; i < 4; i++)
{
if (mychoice == i || opendoor == i)//去掉我选的 和主持人选的
{
continue;
}
door = i;
break;
}
return door;
}
private static int strlen(string[] str)//截取有用字符串
{
int len = 0;
for (int i = 0; i < str.Length; i++)
{
if (!string.IsNullOrWhiteSpace(str[i]))
{
len++;
}
}
return len;
}
}
//主程序:
Console.OutputEncoding = Encoding.UTF8;//输出编码格式化
Console.WriteLine("三门问题测试开始");
Console.WriteLine("测试次数为10000次");
double result;
esult = startGame(true);//第二次选择不变的概率
Console.WriteLine("第二次选择不变赢的概率为 :{0}%", result);
result = startGame(false);//第二次选择另外一个赢的概率
Console.WriteLine("第二次选择另外一个赢的概率 :{0}%", result);
Console.Read();