用c++解析数学表达式

parsing math expression in c++

本文关键字:表达式 c++      更新时间:2023-10-16

我有一个关于解析树的问题:

我有一个字符串(数学表达式限制),例如:(a+b)*c-(d-e)*f/g。我必须在树中解析该表达式:

class Exp{};
class Term: public Exp{
    int n_;
}
class Node: Public Exp{
    Exp* loperator_;
    Exp* roperator_;
    char operation; // +, -, *, /
}

我可以使用什么算法来构建一个表示上面表达式字符串的树?

使用调车场算法。维基百科的描述相当全面,我希望它足够了。

您还可以尝试编写形式语法,例如解析表达式语法,并使用工具生成解析器。这个关于PEG的网站列出了3个用于PEG解析的C/C++库。

(a+b)*c-(d-e)*f/g是一个固定表达式。

若要轻松创建树,请先将其转换为前缀表达式。

根据该实例,(A * B) + (C / D)的前缀是+ (* A B) (/ C D)

     (+)            
     /         
    /          
  (*)    (/)         
  /    /          
 A   B C    D   
 ((A*B)+(C/D))  

然后,您的树看起来有+作为其根节点。您可以继续填充关于每个操作符的左右子树。

此外,此链接详细解释了递归下降解析,并且可以实现。

#include <algorithm>
#include <iostream>
#include <string>
#include <cctype>
#include <iterator>
using namespace std;
class Exp{
public:
//  Exp(){}
    virtual void print(){}
    virtual void release(){}
};
class Term: public Exp {
    string val;
public:
    Term(string v):val(v){}
    void print(){
        cout << ' ' << val << ' ';
    }
    void release(){}
};
class Node: public Exp{
    Exp *l_exp;
    Exp *r_exp;
    char op; // +, -, *, /
public:
    Node(char op, Exp* left, Exp* right):op(op),l_exp(left), r_exp(right){}
    ~Node(){
    }
    void print(){
        cout << '(' << op << ' ';
        l_exp->print();
        r_exp->print();
        cout  << ')';
    }
    void release(){
        l_exp->release();
        r_exp->release();
        delete l_exp;
        delete r_exp;
    }
};
Exp* strToExp(string &str){
    int level = 0;//inside parentheses check
    //case + or -
    //most right '+' or '-' (but not inside '()') search and split
    for(int i=str.size()-1;i>=0;--i){
        char c = str[i];
        if(c == ')'){
            ++level;
            continue;
        }
        if(c == '('){
            --level;
            continue;
        }
        if(level>0) continue;
        if((c == '+' || c == '-') && i!=0 ){//if i==0 then s[0] is sign
            string left(str.substr(0,i));
            string right(str.substr(i+1));
            return new Node(c, strToExp(left), strToExp(right));
        }
    }
    //case * or /
    //most right '*' or '/' (but not inside '()') search and split
    for(int i=str.size()-1;i>=0;--i){
        char c = str[i];
        if(c == ')'){
            ++level;
            continue;
        }
        if(c == '('){
            --level;
            continue;
        }
        if(level>0) continue;
        if(c == '*' || c == '/'){
            string left(str.substr(0,i));
            string right(str.substr(i+1));
            return new Node(c, strToExp(left), strToExp(right));
        }
    }
    if(str[0]=='('){
    //case ()
    //pull out inside and to strToExp
        for(int i=0;i<str.size();++i){
            if(str[i]=='('){
                ++level;
                continue;
            }
            if(str[i]==')'){
                --level;
                if(level==0){
                    string exp(str.substr(1, i-1));
                    return strToExp(exp);
                }
                continue;
            }
        }
    } else
    //case value
        return new Term(str);
cerr << "Error:never execute point" << endl;
    return NULL;//never
}
int main(){
    string exp(" ( a + b ) * c - ( d - e ) * f / g");
    //remove space character
    exp.erase(remove_if(exp.begin(), exp.end(), ::isspace), exp.end());
    Exp *tree = strToExp(exp);
    tree->print();
    tree->release();
    delete tree;
}
//output:(- (* (+  a  b ) c )(/ (* (-  d  e ) f ) g ))

第一步是为表达式编写语法。对于这样一个简单的情况,第二步是编写一个递归下降解析器,这是我推荐的算法。这是关于递归下降语法分析器的wiki页面,它有一个好看的C实现。

http://en.wikipedia.org/wiki/Recursive_descent_parser

您可以使用此语法创建表达式。

exp:
    /* empty */
  | non_empty_exp { print_exp(); }
  ;
non_empty_exp:
    mult_div_exp
  | add_sub_exp
  ;
mult_div_exp:
    primary_exp
  | mult_div_exp '*' primary_exp { push_node('*'); }
  | mult_div_exp '/' primary_exp { push_node('/'); }
  ;
add_sub_exp:
    non_empty_exp '+' mult_div_exp { push_node('+'); }
  | non_empty_exp '-' mult_div_exp { push_node('-'); }
  ;
primary_exp:
  | '(' non_empty_exp ')'
  | NUMBER { push_term($1); }
  ;

下面是你的lexer。

[ t]+   {}
[0-9]+   { yylval.number = atoi(yytext); return NUMBER; }
[()]     { return *yytext; }
[*/+-]   { return *yytext; }

该表达式是在进行时构建的,使用以下例程:

std::list<Exp *> exps;
/* push a term onto expression stack */
void push_term (int n) {
    Term *t = new Term;
    t->n_ = n;
    exps.push_front(t);
}
/* push a node onto expression stack, top two in stack are its children */
void push_node (char op) {
    Node *n = new Node;
    n->operation_ = op;
    n->roperator_ = exps.front();
    exps.pop_front();
    n->loperator_ = exps.front();
    exps.pop_front();
    exps.push_front(n);
}
/*
 * there is only one expression left on the stack, the one that was parsed
 */
void print_exp () {
    Exp *e = exps.front();
    exps.pop_front();
    print_exp(e);
    delete e;
}

以下例程可以很好地打印您的表达式树:

static void
print_exp (Exp *e, std::string ws = "", std::string prefix = "") {
    Term *t = dynamic_cast<Term *>(e);
    if (t) { std::cout << ws << prefix << t->n_ << std::endl; }
    else {
        Node *n = dynamic_cast<Node *>(e);
        std::cout << ws << prefix << "'" << n->operation_ << "'" << std::endl;
        if (prefix.size()) {
            ws += (prefix[1] == '|' ? " |" : "  ");
            ws += "  ";
        }
        print_exp(n->loperator_, ws, " |- ");
        print_exp(n->roperator_, ws, " `- ");
    }
}

我以前写过一个类来处理这个问题。它有点冗长,可能不是世界上最高效的东西,但它处理有符号/无符号整数、双精度、浮点、逻辑和逐位操作。

它检测数字上溢和下溢,返回有关语法的描述性文本和错误代码,可以强制将双精度处理为整数,也可以忽略看板,支持用户定义的精度和智能舍入,如果设置DebugMode(true),它甚至会显示其工作。

最后。。。。。。它不依赖于任何外部库,所以你可以直接把它放进去。

示例用法:

CMathParser parser;
double dResult = 0;
int iResult = 0;
//Double math:
if (parser.Calculate("10 * 10 + (6 ^ 7) * (3.14)", &dResult) != CMathParser::ResultOk)
{
    printf("Error in Formula: [%s].n", parser.LastError()->Text);
}
printf("Double: %.4fn", dResult);
//Logical math:
if (parser.Calculate("10 * 10 > 10 * 11", &iResult) != CMathParser::ResultOk)
{
    printf("Error in Formula: [%s].n", parser.LastError()->Text);
}
printf("Logical: %dn", iResult);

最新版本始终可通过CMathParser GitHub存储库获得。