简单之设置物品掉落(出现)几率

#include "stdafx.h"

#include 
#include 
#include 

using namespace std;

unsigned int _cdecl Random(unsigned int m, unsigned int n);

/*
范围随机,
nMinVal 起始值,
nMaxVal 终点值:必要时一般都会+1,不同设计有不同的相加值
*/
unsigned int _cdecl Random(unsigned int nMinVal, unsigned int nMaxVal)
{
	unsigned int nPos, nDis;

	if (nMinVal == nMaxVal)
	{
		return nMaxVal;
	}
	else if (nMinVal > nMaxVal)
	{
		nPos = nMaxVal;
		nDis = nMinVal - nMaxVal;
		return (rand() % nDis + nPos);
	}
	else
	{
		nPos = nMinVal;
		nDis = nMaxVal - nMinVal;
	}
	return (rand() % nDis + nPos);
}

bool _cdecl IsDropItem(float fProbaVal);

/*
是否掉落(出现),
fProbaVal 设置几率:例如0.0003 == 0.03%(0.0003 * 100)的掉落(出现)几率
*/
bool _cdecl IsDropItem(float fProbaVal)
{
	const unsigned int nCmpRandVal = Random((unsigned int)(100.0000f * fProbaVal),
		(int)((100.0000f / fProbaVal) + 100.0000f));

	const unsigned int nCmpDropVal = (unsigned int)((100.0000f / fProbaVal) / 100.0000f);

	return ((nCmpDropVal != (nCmpRandVal / 100)) ? false : true);
}


int _tmain(int argc, _TCHAR* argv[])
{
	int nMaxCount = 500000;
	int nDropCount = 0;
	const float fProbaVal = 0.0037f;

	//初始化随机参数
	srand((unsigned int)time(NULL));

	while ((nMaxCount--))
	{
		//0.37%的几率
		if (true == IsDropItem(fProbaVal))
		{
			nDropCount += 1;
		}
	}

	nMaxCount = 500000;

	//结果基本吻合总概率
	const float fProbaResult = (float)(nDropCount / (float)(nMaxCount / 100.00f));
	printf("总掉落比率为:%f%\r\n", fProbaResult);

	return 0;
}


你可能感兴趣的:(简单之设置物品掉落(出现)几率)