我正在尝试做的是在函数内部的注释块中描述:
bool CalculusWizard::partitionEquation(const std::string & eq, std::string & eq1,
std::string & eq2, CalcWizConsts::eqOps & oper)
{
/* Given an equation eq, partion eq into
eq = eq1 oper eq2
where oper is the operator with the lowest precedence,
e.g. eq = "x*sin(x)+x^2" --> eq1 = "x*sin(x)", oper = ADDITION, eq2 = "x^2".
If there is no operator, e.g. eq = "x", then oper = NONE.
The error checking is done in this function. If there is a syntactical error
in eq, then return false.
*/
bool eqGood = true;
eq1.clear();
eq2.clear();
oper = CalcWizConsts::NONE;
int netParans = 0;
std::string::const_iterator it(eq.begin()), offend(eq.end());
while (it != offend)
{
char thisChar(*it);
char nextChar(((it+1) != offend) ? *(it+1) : '\0');
if (thisChar == '(')
{
if ()
++netParans;
}
else if (thisChar == ')')
{
if (isOp(nextChar))
{
}
--netParans;
}
else if (CalcWizConsts::digMap.count(thisChar) == 1)
{
}
}
if (netParans != 0)
eqGood = false;
return eqGood;
}
Run Code Online (Sandbox Code Playgroud)
你可以忽略我开始写的那个gunk.我刚刚放弃了.是时候看看有人已经做了我想要做的事.
运营商我有,在优先顺序,是^,*,/,+和-.这可能是公式中的功能是x,sin(x),cos(x),e^x和log(x)(虽然我希望能够更多的稍后添加).做我正在尝试做的事情有没有标准机制?
你最想要做的就是将表达式分解为表达式树 - 以这种形式处理它会容易得多.
要做到这一点,首先你需要某种解析器,它会将表达式分解为标记.然后,您可以使用反向波兰表示法转换算法来构建表达式树.维基百科页面有很多相关信息.
在您的示例中,表达式树将如下所示:
x*sin(x)+x^2
+
/ \
* ^
/ \ / \
x sin x 2
|
x
Run Code Online (Sandbox Code Playgroud)
使用此树,您可以以任何方式轻松处理整个表达式.