生成总和固定 可变范围的随机数

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

 

posted @ 2015-03-18 10:48  docomo  阅读(2435)  评论(0编辑  收藏  举报