生成總和固定 可變範圍的隨機數

docomo發表於2015-03-18
private void TestTest()
        {
            int maxValue = 10000;
            Random rd = new Random(Guid.NewGuid().GetHashCode());

            int avg = Convert.ToInt32(this.txtAvg.Text); // 300;//平均數100
            int range = Convert.ToInt32(this.txtFiled.Text); //300;//上下波動值10
            int totalRandomValue = 0;
            List<double> list = new List<double>();
            do
            {
                int tmp = rd.Next(range) - 10 + avg;
                //int tmp = rd.Next(range) + avg;
                list.Add((double)tmp / 100);
                totalRandomValue += tmp;
                tmp = maxValue - totalRandomValue;
                if (tmp <= avg + range)
                {
                    list.Add((double)tmp / 100);        //TODO:過大或者過小修正不寫了,太麻煩
                    break;
                }
            }
            while (true);
            list.ForEach((d) =>
            {
                this.listBox1.Items.Add(d.ToString());
            });
            this.button1.Text = list.Sum().ToString() + "- 總記錄數:" + list.Count.ToString();
        }

 

相關文章