C# 做一個指定機率的抽獎程式

來源:互聯網
上載者:User

標籤:style   blog   http   color   ar   for   2014   div   sp   

        static void Main(string[] args)        {            //各物品的機率儲存在數組裡            float[] area = new float[4]{                0.980f,                0.550f,                0.230f,                0.010f            };            //單次測試            //Console.WriteLine(Get(area));            //批量測試            int[] result = new int[4]{                0,                0,                0,                0            };            for (int i = 0; i < 1770000; i++)    //為了比對結果方便,這裡迴圈的次數是總機率的1000倍            {                int n = Get(area);      //本次抽獎結果                result[n]++;            //統計抽到的次數            }            Console.WriteLine("結果:");            foreach (int times in result)            {                Console.WriteLine(times);            }        }        /// <summary>        /// 擷取抽獎結果        /// </summary>        /// <param name="area">各物品的抽中機率</param>        /// <returns>返回抽中的物品所在數組的位置</returns>        private static int Get(float[] prob)        {            int result = 0;            int n = (int)(prob.Sum() * 1000);           //計算機率總和,放大1000倍            Random r = rnd;            float x = (float)r.Next(0, n) / 1000;       //隨機產生0~機率總和的數字            for (int i = 0; i < prob.Count(); i++)            {                float pre = prob.Take(i).Sum();         //區間下界                float next = prob.Take(i + 1).Sum();    //區間上界                if (x >= pre && x < next)               //如果在該區間範圍內,就返回結果退出迴圈                {                    result = i;                    break;                }            }            return result;        }        private static Random rnd = new Random();

 

 

C# 做一個指定機率的抽獎程式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.