码迷,mamicode.com
首页 > 其他好文 > 详细

表达式求值

时间:2017-05-09 12:33:03      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:++   --   ber   测试用例   int   option   ring   class   size   

#include <bits/stdc++.h>

using namespace std;

char OprateRelation[7][7] =// +    -    *    /    (    )   =
                            {{>,>, <, <, <, >, >}, //‘+‘
                            {>, >, <, <, <, >, >}, //‘-‘
                            {>, >, >, >, <, >, >}, //‘*‘
                            {>, >, >, >, <, >, >}, //‘/‘
                            {<, <, <, <, <, =,  }, //‘(‘
                            {>, >, >, >,  , >, >}, //‘)‘
                            {<, <, <, <, <,  , =}};//‘=‘

string Operteraiton = "+-*/()=";

int Getoperteration(char x) {
    for(int i = 0; i < 7; i++)
        if(Operteraiton[i] == x) return i;
    return -1;
}
char CompareOperation(char x, char y) {
    return OprateRelation[Getoperteration(x)][Getoperteration(y)];
}
double Get_ans(double x, double y, char opt) {
    if(opt == -) return x - y;
    else if(opt == +) return x + y;
    else if(opt == *) return x * y;
    else return x/y;
}
double Slove(string Pattern) {
    stack <double> Num;
    stack <char> Opertion;
    Opertion.push(=);
    int i = 0, flag = 1, gg = 1;
    char Next_char;
    if(Pattern[0] == + || Pattern[0] == -) Num.push(0);
    if(Pattern[Pattern.size() - 1] != =) Pattern += =;
    while(flag && i < Pattern.size()) {
        Next_char = Pattern[i];
        if(Getoperteration(Next_char) < 0) {
            string Number = "";
            Number += Next_char;
            while(Getoperteration(Pattern[++i]) < 0) {
                Number += Pattern[i];
            }
            Num.push(atof(Number.c_str()));
        }else {
            char opt = CompareOperation(Opertion.top(), Next_char);
            if(opt == <) {
                Opertion.push(Next_char);
                i++;
            }else if(opt == >) {
                char Next_option = Opertion.top();
                Opertion.pop();
                double y = Num.top();
                Num.pop();
                double x = Num.top();
                Num.pop();
                double ans = Get_ans(x, y, Next_option);
                Num.push(ans);
            }else {
                Opertion.pop();
                if(i == (int)Pattern.length()) flag = 0;
                else i++;
            }
        }
    }
    return Num.top();
}
int main()
{
    int T;
    cin >> T;//测试用例的个数
    string s;
    while(T--) {
        cin >> s;
        printf("%.2f\n", Slove(s));
    }
    return 0;
}

 

表达式求值

标签:++   --   ber   测试用例   int   option   ring   class   size   

原文地址:http://www.cnblogs.com/cshg/p/6829953.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!