首页 > 代码库 > C# 随机红包算法

C# 随机红包算法

 1 static void Main(string[] args) 2         { 3             double totalAmount = 20; 4             int num = 10; 5             double minAmount = 0.01; 6             Random r = new Random(); 7             for (int i = 1; i < num; i++) 8             { 9                 double safeAmount = (totalAmount - (num - i) * minAmount) / (num - i);10                 //double money = new Random().Next(Convert.ToInt32(minAmount * 100), Convert.ToInt32(safeAmount * 100)) / 100; 11                 double money = NextDouble(r, minAmount * 100, safeAmount * 100) / 100;12                 money = Math.Round(money, 2, MidpointRounding.AwayFromZero);13                 totalAmount=totalAmount-money;14                 totalAmount = Math.Round(totalAmount, 2, MidpointRounding.AwayFromZero);15                 Console.WriteLine("" + i + "个红包:" + money + " 元,余额:" + totalAmount + "");16             }17             Console.WriteLine("" + num + "个红包:" + totalAmount + " 元,余额:0 元");18 19             Console.ReadKey();20         }21 22         /// <summary>23         /// 生成设置范围内的Double的随机数24         /// eg:_random.NextDouble(1.5, 2.5)25         /// </summary>26         /// <param name="random">Random</param>27         /// <param name="miniDouble">生成随机数的最大值</param>28         /// <param name="maxiDouble">生成随机数的最小值</param>29         /// <returns>当Random等于NULL的时候返回0;</returns>30         protected static double NextDouble(Random random, double miniDouble, double maxiDouble)31         {32             if (random != null)33             {34                 return random.NextDouble() * (maxiDouble - miniDouble) + miniDouble;35             }36             else37             {38                 return 0.0d;39             }40         }

 

C# 随机红包算法