C# 随机红包算法
Posted 权
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 else 37 { 38 return 0.0d; 39 } 40 }
以上是关于C# 随机红包算法的主要内容,如果未能解决你的问题,请参考以下文章