其他分享
首页 > 其他分享> > 运算表达式求值模板

运算表达式求值模板

作者:互联网

表达式计算

使用方法

输入合法的表达式,加减乘除,可以带括号,用空格分开数字和符号,-1为结束标志,比如:
2 * 5 + 3 -1
注意:这是用来算具体答案的,不是转化成后缀表达式输出的,当然,思想是递归建立表达式树,然后后序遍历得逆波兰式,然后用栈计算结果

模板

#include<iostream>
#include<string.h>
#include<string>
#include<stack>
//#include<math.h>
using namespace std;
#define mem(x,num) memset(x,num,sizeof(x))
const int N = 1e3 + 5;
const int defaultSize = 100;
int lson[N], rson[N];

int nc = 0;
int cut = 0;

struct Num {
    char  val[defaultSize];
    Num() {
        val[0] = '0';
    }
    bool is_op() {
        return strlen(val)== 1 && (val[0]<'0' || val[0]>'9');
    }
    double ToNum() {
        return atof(val);
    }
};
Num op[N];
Num arra[defaultSize];
void Init() {
    mem(lson, 0);
    mem(rson, 0);
    mem(op, 0);
    nc = 0;
    cut = 0;
    mem(arra, 0);
}
int build_Tree(Num s[], int l, int r) { // Build the expression tree
    int tag1 = -1, tag2 = -1, p = 0;// tag1 stand for add&sub is_exist,tag2 for muti&devide
    int u;
    if (r - l == 1) {// this is only one point in this interval,build it
        u = ++nc;
        lson[u] = rson[u] = 0;
        op[u]=s[l];
        return u;// return self num to fa Node
    }
    for (int i(l); i < r; i++) {
        switch (s[i].val[0])// s[i]
        {
        case '(':p++; break;
        case ')':p--; break;
        case '+':case '-':if(!p)tag1 = i; break;// if operator in (),continue
        case '*':case '/':if(!p)tag2 = i; break;
        }
    }
    if (tag1 < 0)tag1 = tag2;// no + or - outside
    if (tag1 < 0)return build_Tree(s, l + 1, r - 1); // no * or / outside mean all operator and num in ()
    u = ++nc;
    lson[u] = build_Tree(s, l, tag1);
    rson[u] = build_Tree(s, tag1 + 1, r);
    op[u] = s[tag1];
    return u;
}
void Post(int rt) {// Postorder
    if (lson[rt] != 0)Post(lson[rt]);
    if (rson[rt] != 0)Post(rson[rt]);
    arra[cut++] = op[rt];// cout << op[rt] << ' ';
}
double query(Num s[],int n) { // cal the value
    stack<double>P;
    for (int i(0); i < n; i++) {
        if (!s[i].is_op()) {
            P.push(s[i].ToNum());
        }
        else {
            double x1 = P.top();
            P.pop();
            double x2 = P.top();
            P.pop();
            double y;
            switch (s[i].val[0])
            {
            case '+':y = x1 + x2; break;
            case '-':y = x2 - x1; break;
            case '*':y = x1 * x2; break;
            case '/':y = x2 / x1; break;
            }
            P.push(y);
        }
    }
    return P.top();
}
int main() {
    Num s[defaultSize];
    char str[defaultSize];
    while (1) { //cin>>s
        Init();
        int n=0;
        while (cin >> str,strcmp(str,"-1")) { // remove this section
            strcpy_s(s[n++].val, 20, str);
        }
        build_Tree(s, 0,n); // strlen(s)
        Post(1);
        cout << query(arra,n)<<endl;// 
    }
    return 0;
}

标签:case,return,tag1,val,int,break,模板,求值,表达式
来源: https://www.cnblogs.com/Titordong/p/10472623.html