红包算法

1.红包算法-封装方法

     /// <summary> 

        ///  微信红包算法 

        /// </summary> 

        /// <param name="allmoney">红包金额</param>

        /// <param name="moneycount">红包数量</param>

        /// <returns></returns>

        public static string GetMoneys(double allmoney, int moneycount) 

        { 

            string retamt = ""; 

            //人均最小金额 

            double min = 0.01; 

            if (allmoney < moneycount * min) 

                return null; 

                    int num = moneycount; 

            List<double> array = new List<double>(); 

            Random r = new Random(); 

            for (int i = 0; i < num; i++) 

            {

                if (moneycount == 1) 

                {

                     moneycount--; 

                    array.Add(Convert.ToDouble(allmoney.ToString("0.0000"))); 

                    if (retamt.Length > 0) 

                    { 

                        retamt += ","; 

                    } 

                    retamt += Convert.ToDouble(allmoney.ToString("0.000")).ToString();     

                }else 

                {

                    //保存剩余金额可以足够的去分配剩余的红包数量 

                    double max = (allmoney - (moneycount - 1) * min) / moneycount * 2; 

                    double money = r.NextDouble() * max; 

                    money = Convert.ToDouble((money <= min ? min : money).ToString("0.0000")); 

                    moneycount--; 

                    allmoney -= money; 

                    array.Add(money); 

                    if (retamt.Length > 0) 

                    {

                        retamt += ","; 

                    } 

                    retamt += money.ToString();      

                } 

            } 

            string ret = string.Join(",", retamt); 

            //再次随机 

            return ret; 

        } 

2.调用

   //总金额66元红包个数3个

    string money= GetMoneys(66, 3);

            Response.Write("返回值:" +money);

posted @ 2020-04-09 09:10  短暂的空白  阅读(254)  评论(0编辑  收藏  举报