三门问题实现

//代码实现:

 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();

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值