码迷,mamicode.com
首页 > 编程语言 > 详细

C# 随机红包算法

时间:2016-10-27 10:29:36      阅读:408      评论:0      收藏:0      [点我收藏+]

标签:pre   prot   rand   new   read   mina   随机   1.5   turn   

 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# 随机红包算法

标签:pre   prot   rand   new   read   mina   随机   1.5   turn   

原文地址:http://www.cnblogs.com/szfhquan/p/6002768.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!