[TestMethod]
public void CheckTrue()
{
var reg = CommonTools.CheckTrue(1.001M);
}
/// <summary>
/// 根据中奖率判断是否中奖
/// </summary>
/// <param name="percent">中奖率(0~100)</param>
/// <returns></returns>
public static bool CheckTrue(decimal percent)
{
bool result = false;
if (percent >= 100)
{
result = true;
}
else if (percent <= 0)
{
result = false;
}
else
{
string strPercent = percent.ToString();
int rndCount = 0;//随机数个数
int rndMax = 0;//随机数最大值
int rand = 0;//抽中数
if (strPercent.IndexOf(‘.‘) == -1)//无小数位
{
rndMax = 100;
rndCount = (int)percent;
var rndList = GenerateRandom(rndMax, rndCount,false);
rand = rnd.Next(rndMax);
result = rndList.Contains(rand);
}
else
{
int accCount = strPercent.Length - strPercent.IndexOf(‘.‘)-1;
//rndMax= percent>=1? (int)Math.Pow(10, strPercent.Length+1): (int)Math.Pow(10, accCount+1);
rndMax = (int)Math.Pow(10, accCount + 2);
rndCount = (int)(percent * (int)Math.Pow(10, accCount));
var rndList = GenerateRandom(rndMax, rndCount, false);
rand = rnd.Next(rndMax);
result = rndList.Contains(rand);
}
}
return result;
}
public static List<int> GenerateRandom(int iMax, int iNum,bool isRepeat=true)
{
long lTick = DateTime.Now.Ticks;
List<int> lstRet = new List<int>();
for (int i = 0; i < iNum; i++)
{
Random ran = new Random((int)lTick * i);
int iTmp = ran.Next(iMax);
if (!isRepeat)
{
if (lstRet.Contains(iTmp))
{
i--;
lTick += (new Random((int)lTick).Next(978));
continue;
}
}
lstRet.Add(iTmp);
lTick += (new Random((int)lTick).Next(978));
}
return lstRet;
}