using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace TestRandom
{
public partial class WebForm1 : System.Web.UI.Page
{
/// <summary>
/// author:bruce 2016-05-23
/// title:关于如何在不定金额和不定人数中随机红宝数问题
/// 基本要点:
/// (1)这里需要特别注意,随机红包轮数要比实际小一轮。最后一轮是总金额减去前面的总和
/// (2)每次随机的范围是1-总金额-人数+轮数-sum(前面的随机结果),自行思考一下为什么需要这么写?
/// (3)每次得到结果需要存放在数组中去
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
//定义参数
double total = 100;//红包总金额
int count = 10;//人数
//定义存储已经随机出来的结果,数组的长度和人数一致
double[] result = new double[count];
//循环处理产生随机数
for (int i = 0; i < count-1; i++)
{
//定义最大值
double maxValue = total - count + i - SumArray(result);
//定义临时结果
double valuetemp = getRandom(maxValue);
//装载到结果中,并打印每次的结果
result[i] = valuetemp;
Response.Write("第" + (i + 1) + "轮随机出的红包金额为:" + valuetemp + "</br>");
}
Response.Write("第" + count + "轮随机出的红包金额为:" +(total- SumArray(result)) + "</br>");
result[count-1] = (total - SumArray(result));
Response.Write("总红包金额:"+SumArray(result));
}
//定义指定范围随机数
#region
public double getRandom(double end)
{
Random ran = new Random();
double n = Math.Round(ran.NextDouble() * end, 2);
return n;
}
#endregion
#region 对不定数组求和
public double SumArray(double[] arr)
{
double sum = 0;
foreach (double m in arr)
{
sum += m;
}
return sum;
}
#endregion
}
}
运行结果如下所示: