计算带有括号的表达式的值

关键在于寻找括号

#include<cstdio>
#include<cstring>
using namespace std;

const int maxn = 100;

char s[maxn];
int left[maxn],right[maxn];
char node[maxn];
int cnt = 0;
int newnode()
{
    cnt++;
    left[cnt] = 0;
    right[cnt] = 0;
    return cnt;
}

int creat_tree(int start,int end)
{
    int p = 0,c1 = -1,c2 = -1;
    if(end - start == 1)
    {
        int u = newnode();
        node[u] = s[start];
        return u;
    }
    for(int i = start;i < end;i++)
    {
        if(s[i] == '(')
            p++;
        else if(s[i] == ')')
            p--;
        else if((s[i] == '+' || s[i] == '-') && !p)//加减号,且不在括号里面
        {
            c1 = i;
        }
        else if((s[i] == '*' || s[i] == '/') && !p)
        {
            c2 = i;
        }
    }
    if(c1 == -1 && c2 == -1)//都在括号里面
    {
        return creat_tree(start + 1,end - 1);
    }
    else if(c1 != -1)//最右面的加减号
    {
        int u = newnode();
        node[u] = s[c1];
        left[u] = creat_tree(start,c1);
        right[u] = creat_tree(c1 + 1,end);
        return u;
    }
    else
    {
        int u = newnode();
        node[u] = s[c2];
        left[u] = creat_tree(start,c2);
        right[u] = creat_tree(c2 + 1,end);
        return u;
    }
}

double comput(int root)
{
    if(node[root] == '*')
    {
        return comput(left[root]) * comput(right[root]);
    }
    if(node[root] == '/')
    {
        return comput(left[root]) / comput(right[root]);
    }
    if(node[root] == '-')
    {
        return comput(left[root]) - comput(right[root]);
    }
    if(node[root] == '+')
    {
        return comput(left[root]) + comput(right[root]);
    }
    return (double)node[root] - '0';
}


int main()
{
    freopen("input.txt","r",stdin);
    scanf("%s",s);
    int root = creat_tree(0,strlen(s));
    double result = comput(root);
    return 0;
}

 

posted @ 2019-03-09 17:10  Toretto瑞  阅读(416)  评论(0编辑  收藏  举报