处理一个数是否落在一个数值范围里(a, b]里(区间左右括号符合数学定义)
//
// 判断一个浮点数是否落在范围串中
// 范围串符合数学上区间的定义:[a,b]、(a,b)、(-x, 100).....
// “∞”用“x”表示
//
#define PASS_OK (100)
#define PASS_NO (102)
#define ERR_RANGE_STR (-100)
int InRange(char *pBuf, double fVal)
{
double fMin = 0.0, fMax = 0.0;
CString strRange = pBuf;
strRange.Replace(" ", ""); //去掉里面的空格
int nPosComma = strRange.Find(",");
if (nPosComma == -1)
return ERR_RANGE_STR;
//取出左值串
CString strLeft = strRange.Mid(1, nPosComma-1);
if(strLeft.IsEmpty())
return ERR_RANGE_STR;
if (strLeft == "-x"|| strLeft == "x")
fMin = -9.9e10;
else
fMin = atof(strLeft);
//取出右值串
CString strRight = strRange.Mid(nPosComma+1, strRange.GetLength()-nPosComma-2);
if(strRight.IsEmpty())
return ERR_RANGE_STR;
if (strRight == "+x"|| strRight == "x")
fMax = +9.9e10;
else
fMax = atof(strRight);
//判断是小括号“(”还是中括号“[”
bool b1, b2;
b1 = b2 =false;
if (strRange.Left(1) == "(")
b1 = (fVal > fMin)?true:false;
else if (strRange.Left(1) == "[")
b1 = (fVal >= fMin)?true:false;
else
return ERR_RANGE_STR;
if (strRange.Right(1) == ")")
b2 = (fVal < fMax)?true:false;
else if(strRange.Right(1) == "]")
b2 = (fVal <= fMax)?true:false;
else
return ERR_RANGE_STR;
if(b1&&b2)
return PASS_OK; //落在
else
return PASS_NO; //没有落在
}
用到了MFC中的CString的几个函数,使用其他语言一样的,替换一下其中几个函数,如Left、Mid、Find;
注意上述中的∞用字符x表示;
使用时,如判断90是否在[100, 120]中:InRange("[100, 120]", 90);
这种处理方式的用处是,将第一个参数的数值区间串放在外部配置文件、XML文件中,便于修改!