1. 程式人生 > >C# 獲取指定範圍的隨機數

C# 獲取指定範圍的隨機數

1.從指定範圍內隨機生成幾個隨機數

 //需要生成幾個隨機數
            int nQty = int.Parse(txtQty.Text);
            //最大值
            int nInsptQty = int.Parse(txtInsptQty.Text);

            Hashtable hashtable = new Hashtable();
            Random rm = new Random();
            int RmNum = nQty;

            List<int> list = new List<int>();
            for (int i = 0; hashtable.Count < RmNum; i++)
            {
                int nValue = rm.Next(nInsptQty);
                if (!hashtable.ContainsValue(nValue) && nValue != 0)
                {
                    hashtable.Add(nValue, nValue);

                    list.Add(nValue);
                }
            }

結果:

2.將數字拆分後在生成隨機數

如:數字20生成兩個隨機數,則第一組隨機數範圍在[1-10],第二組範圍在[11-20]

    List<int> list = new List<int>();

                int nInsptQty = int.Parse(txtInsptQty.Text);
                int nQty = int.Parse(txtQty.Text);

                //先將數字(最大化)平均拆分
                var nArray = new int[nQty];
                var avg = nInsptQty / nQty;
                var another = nInsptQty % nQty;
                for (var i = 0; i < nQty; i++)
                {
                    nArray[i] = avg;
                    if (i < another)
                    {
                        nArray[i] += 1;
                    }
                }

            
                Random rm = new Random();
                int nSum = 0;
                int nMin = 1;
                int nMax = 0;
                for (int i = 0; i < nQty; i++)
                {
                    //最大值
                    nMax = nSum + nArray[i] ;
                    //獲取隨機數
                    int nValue = rm.Next(nMin, nMax+1);
                    txtResult.AppendText(nValue.ToString() + Environment.NewLine);

                    list.Add(nValue);
                    nSum += nArray[i];
                    nMin = nSum+1;
                }

結果: