您的位置:首页 > 其它

南阳理工OJ_题目305 表达式求值

2014-04-21 13:35 309 查看
#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

void push_op(char c);
char pop_op();
void push_num(int n);
int pop_num();

char ch[310];
char op[110];
int num[110];
int op_top;
int num_top;

int main()
{
    int T;
    int len;
    cin >> T;
    while(T--)
    {
        cin >> ch;
        op_top = 0;
        num_top = 0;
        len = strlen(ch);

        if(ch[0] >= '0' && ch[0] <= '9')
        {
            cout << ch << endl;
            continue;
        }

        int flag = 1;

        for(int i = 0; i < len; i++)
        {
            if( !(ch[i] >= '0' && ch[i] <= '9') )
                flag = 1;
            if(ch[i] == '(')
            {
                push_op(ch[i-1]);
            }

            if(ch[i] >= '0' && ch[i] <= '9' && flag == 1)
            {
                int a;
                sscanf(&ch[i], "%d", &a);
                push_num(a);
                flag = 0;
            }

            if(ch[i] == ')')
            {
                int a, b;
                a = pop_num();
                b = pop_num();
                switch(pop_op())
                {
                    case 'n':
                        if(a > b)
                            push_num(b);
                        else
                            push_num(a);
                        break;
                    case 'x':
                        if(a < b)
                            push_num(b);
                        else
                            push_num(a);
                        break;
                    case 'd':
                        push_num(a+b);
                }
            }
        }

        cout << num[0] << endl;
    }
}

void push_op(char c)
{
    op[op_top++] = c;
}

char pop_op()
{
    return op[--op_top];
}

void push_num(int n)
{
    num[num_top++] = n;
}

int pop_num()
{
    return num[--num_top];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: