学习伴随一生
没有绝对,只有相对
转自:http://www.cnblogs.com/wicub/p/6096897.html
 
/// <summary>
        /// 生成红包数组
        /// </summary>
        /// <param name="totalMoney">总金额</param>
        /// <param name="perMax">最大金额</param>
        /// <param name="perMin">最小金额</param>
        /// <param name="totalUser">总人数</param>
        static decimal[] CalueHB(int totalMoney, decimal perMax, decimal perMin, int totalUser)
        {
            int i = 0; //第几人
            decimal[] array = new decimal[totalUser];//分配结果集            
            Random ran = new Random();

            for (i = 0; i < totalUser; i++) //保证每个人有最小金额+随机值
            {
                array[i] = perMin + Math.Round((Convert.ToDecimal(ran.NextDouble()) * (totalMoney / totalUser - perMin - 1)), 2);
            }

            decimal yet = array.Sum(); // 已分配的总金额
            decimal thisM = 0M; //当前随机分配金额

            while (yet < totalMoney)
            {
                thisM = Math.Round((Convert.ToDecimal(ran.NextDouble()) * (perMax - perMin - 1)), 2);

                i = ran.Next(0, totalUser); //随机选择人
                if (yet + thisM > totalMoney)
                {
                    thisM = totalMoney - yet;
                }

                if (array[i] + thisM < perMax)//判断是否超出最大金额
                {
                    array[i] += thisM;
                    yet += thisM;
                }
            }


            Array.Sort(array);

            yet = 0;
            for (i = 0; i < totalUser; i++)
            {
                yet += array[i];
                Console.Write("第{0}人=>分配{1}元,合计分配{2}元\r\n", (i + 1).ToString().PadLeft(3, ' '), array[i].ToString("f2").PadLeft(8, ' '), yet.ToString("f2").PadLeft(8, ' '));
            }

            return array;
        }

 

posted on 2017-01-17 19:20  蒋正  阅读(3123)  评论(0编辑  收藏  举报