三門概率問題之C#版


前言:

早上看到一片關於三門問題的博客http://www.cnblogs.com/twocats/p/3440398.html,抱着該博客結論的懷疑態度用C#語言寫了一些代碼。實驗證明該博客的結論是正確,如果變換選擇選中車的概率的確是2/3.

代碼:

變量聲明

       //總測試次數
       static long AllCount = 0;
       //抽到車次數
       static long CarCount = 0;
       protected static Random r = new Random(); 
        //1代表羊,2代表car
       static int x = 1;
       static int y = 2;
       static int z = 1;

方法函數

       /// <summary>
       /// 啟動游戲
       /// </summary>
       /// <param name="firstChoose">第一次選擇</param>
       /// <param name="secondChoose">第二次選擇</param>
       static void gameBegin(int firstChoose,int secondChoose)
        {
            if (firstChoose == 1)//主持人把z打開,開始第二次選擇
            {
                AllCount++;
                switch (secondChoose)
                {
                    //不換,依舊選擇x
                    case 0:
                        break;
                    case 1: CarCount++;
                        break;
                }


            }
            if (firstChoose == 2)//主持人把xz中其中一個打開,開始第二次選擇
            {
                //開始選擇.0為不換,1為換
                AllCount++;
                switch (secondChoose)
                {
                    //不換,依舊選擇y
                    case 0: CarCount++;
                        break;
                    case 1:
                        break;
                }
            }
            if (firstChoose == 3)//選擇y,主持人把x門打開,開始第二次選擇
            {
                AllCount++;
                switch (secondChoose)
                {
                    //不換,依舊選擇z
                    case 0:
                        break;
                    case 1: CarCount++;
                        break;
                }

            }
        }

 

主函數

        static void Main(String[] args)
        {

           
            for (int i = 0; i < 1000; i++)
            { 
                int firstchoose = r.Next(1, 4);
                gameBegin(firstchoose,1);
            }
            double result=(double)CarCount/AllCount;
            Console.WriteLine("總共測試了{0}次,抽到車{1}次,換抽到的概率為{2}%",AllCount,CarCount,result*100);
            Console.ReadKey();
        }

結論:

由於一些問題不能貼圖,這里直接附上結果抽了1000次,抽到車690次,抽到概率69%。有問題希望大家留言


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM