avatar

目录
红包算法

自己封装的红包算法

因为公众号小程序提现最小1元,所以最小值设置为了1
还请大家提出建议

c#
//随机发放红包(最小一元)        
#region 发红包
///
/// 发红包
///

/// 红包类型
/// 剩余红包金额
/// 剩余红包数量
///
public static decimal GiveRedBag(EnumRedBagType RedBagType, decimal RemainingRedBag, decimal RemainingNumber)
{
switch (RedBagType)
{
case EnumRedBagType.随机:
return getRandomMoney(RemainingRedBag, RemainingNumber);
case EnumRedBagType.平均:
return getOrdinaryMoney(RemainingRedBag, RemainingNumber);
default:
return 0;
}
}
#endregion

#region 随机红包
///
/// 随机红包
///

/// 红包金额
/// 红包数量
///
public static decimal getRandomMoney(decimal RemainingRedBag, decimal RemainingNumber)
{
RemainingNumber--;
if (RemainingRedBag < 1)
{
return 0;
}
if (RemainingNumber == 0)
{
return Math.Round(RemainingRedBag * 100) / 100;
}
var Min = 1;//最小红包
var Max = RemainingRedBag - RemainingNumber;///最大红包
var MinRandom = Convert.ToInt32((1 / Max) * 100);///最小随机数
var Multiple = new Random().Next(MinRandom, 100);///随机倍数
decimal RedBagMultiple = Math.Round((Multiple / 100M) * 100) / 100;///红包随机倍数
var RedBag = Math.Round(Max * RedBagMultiple * 100) / 100;//红包保留两位小数
RedBag = RedBag < Min ? Min : RedBag;//红包最小金额验证
RedBag = RedBag > Max ? Max : RedBag;//红包最大金额验证
return RedBag;
}
#endregion

#region 普通红包
public static decimal getOrdinaryMoney(decimal RemainingRedBag, decimal RemainingNumber)
{
if (RemainingRedBag < 1)
{
return 0;
}
if (RemainingNumber == 1)
{
return RemainingRedBag;
}
var RedBag = Math.Round((RemainingRedBag / RemainingNumber) * 100) / 100;
return RedBag;
}
#endregion
///范围红包
///
/// 随机红包
///

/// 最小红包
/// 最大红包
///
private static decimal getRandomMoney(decimal MinRedBag, decimal MaxRedBag)
{
if (MinRedBag < 0)
{
return 0;
}
if (MaxRedBag < MinRedBag)
{
return 0;
}
var Min = MinRedBag;//最小红包
var Max = MaxRedBag;///最大红包
var Multiple= new Random().Next(1, 100);///随机倍数
decimal RedBagMultiple = Math.Round((Multiple / 100M) * 100) / 100;///红包随机倍数
var RedBag = Math.Round(Max * RedBagMultiple * 100) / 100;//红包保留两位小数
RedBag = RedBag < Min ? Min : RedBag;//红包最小金额验证
RedBag = RedBag > Max ? Max : RedBag;//红包最大金额验证
return RedBag;
}

评论