用于计算四则混合运算表达式的递归函数
by billow3(QQ:41965573)
//---------------------------------------------------------------------------
AnsiString __fastcall Calc(String sExp)
{
int posL, pos, posR;
String sTmp, sL, sR;
bool IsMinus;
if(sExp.AnsiPos("error"))
return(sExp);
while(pos = sExp.AnsiPos(" "))
sExp = sExp.Delete(pos, 1);
if(sExp.IsEmpty())
return("0");
while((pos = sExp.AnsiPos("[")) > 0
|| (pos = sExp.AnsiPos("{")) > 0)
sExp = sExp.SubString(1, pos - 1) + "("
+ sExp.SubString(pos + 1, sExp.Length());
while((pos = sExp.AnsiPos("]")) > 0
|| (pos = sExp.AnsiPos("}")) > 0)
sExp = sExp.SubString(1, pos - 1) + ")"
+ sExp.SubString(pos+1, sExp.Length());
while(posL=sExp.LastDelimiter("("))
{
sTmp = sExp.SubString(posL + 1, sExp.Length());
posR = sTmp.AnsiPos(")");
if(posR == 0)
return("error:没有配对的), 公式错!");
sExp = sExp.SubString(1, posL - 1)
+ Calc(sTmp.SubString(1, posR - 1))
+ sTmp.SubString(posR + 1, sTmp.Length());
}
IsMinus = false;
while(sExp.LastDelimiter("*/"))
{
for(pos = 1; !sExp.IsDelimiter("*/", pos)
&& pos <= sExp.Length(); pos++);
if(pos == 1 || pos == sExp.Length())
return("error:首或尾字符是*/运算符, 公式错!");
posL = sExp.SubString(1, pos - 1).LastDelimiter("+-");
Minus0:
for(posR = pos + 1; !sExp.IsDelimiter("+-*/", posR)
&& posR <= sExp.Length(); posR++);
if(posR == sExp.Length())
return("error:尾字符是+-*/运算符, 公式错!");
if(sExp.SubString(pos, 2) == "*-"
|| sExp.SubString(pos, 2) == "/-")
{
sExp.Delete(pos+1, 1);
IsMinus = !IsMinus;
goto Minus0;
}
sL = sExp.SubString(posL + 1, pos - posL - 1);
sR = sExp.SubString(pos + 1, posR - pos - 1);
if(sExp.IsDelimiter("/", pos) && sR == "0")
return("error:除数为零,无意义!");
sExp = (posL == 0? String(""): sExp.SubString(1, posL))
+ (sExp.IsDelimiter("*", pos)?
(sL.ToDouble() * sR.ToDouble()):
(sL.ToDouble() / sR.ToDouble()))
+ sExp.SubString(posR, sExp.Length());
}
if(IsMinus)
sExp = String("-") + sExp;
IsMinus = false;
while(sExp.LastDelimiter("+-"))
{
for(pos=2; !sExp.IsDelimiter("+-", pos)
&& pos <= sExp.Length(); pos++);
if(pos == sExp.Length())
return("error:尾字符是+-运算符, 公式错!");
if(pos > sExp.Length())
return(sExp);
Minus1:
for(posR=pos+1; !sExp.IsDelimiter("+-", posR)
&& posR <= sExp.Length(); posR++);
if(posR == sExp.Length())
return("error:尾字符是+-运算符, 公式错!");
if(sExp.SubString(pos, 2) == "+-"
|| sExp.SubString(pos, 2) == "--")
{
sExp.Delete(pos + 1, 1);
IsMinus = !IsMinus;
goto Minus1;
}
sL = sExp.SubString(1, pos - 1);
sR = sExp.SubString(pos + 1, posR - pos - 1);
sExp = String(sExp.IsDelimiter("+", pos)?
(sL.ToDouble() + sR.ToDouble() * (IsMinus? -1: 1)):
(sL.ToDouble() - sR.ToDouble() * (IsMinus? -1: 1)))
+ sExp.SubString(posR, sExp.Length());
}
return(sExp);
}