表达式求值(后缀表达式求值)

表达式求值

时间限制:3000 ms  |  内存限制:65535 KB
难度:4
 
描述
ACM队的mdd想做一个计算器,但是,他要做的不仅仅是一计算一个A+B的计算器,他想实现随便输入一个表达式都能求出它的值的计算器,现在请你帮助他来实现这个计算器吧。 比如输入:“1+2/4=”,程序就输出1.50(结果保留两位小数)
 
输入
第一行输入一个整数n,共有n组测试数据(n<10)。 每组测试数据只有一行,是一个长度不超过1000的字符串,表示这个运算式,每个运算式都是以“=”结束。这个表达式里只包含+-*/与小括号这几种符号。其中小括号可以嵌套使用。数据保证输入的操作数中不会出现负数。 数据保证除数不会为0
输出
每组都输出该组运算式的运算结果,输出结果保留两位小数。
样例输入
2
1.000+2/4=
((1+2)*5+1)/4=
样例输出
1.50
4.00
题解:
求后缀表达式,用后缀表达式,求解;
AC代码:
#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<queue>
#include<stack>
using namespace std;
const int INF=0x3f3f3f3f;
#define mem(x,y) memset(x,y,sizeof(x))
#define SI(x) scanf("%d",&x)
#define PI(x) printf("%d",x)
typedef long long LL;
const int MAXN=1010;
char s[MAXN];
char work(char a,char b){
    if(a=='#')return '<';
    if(a=='+'||a=='-'){
        if(b=='*'||b=='/'||b=='(')return '<';
        else return '>';
    }
    if(a=='*'||a=='/'){
        if(b=='(')return '<';
        else return '>';
    }
    if(a=='('||a=='=')
    {
        if( (a=='('&&b==')')||(a=='='&&b=='=') ) return '='; 
        else return '<'; 
    } 
}
int main(){
    int T;
    SI(T);
    while(T--){
        double temp,p,a,b;
        scanf("%s",s);
        stack<char>S;
        stack<double>s2;
        S.push('#');
        for(int i=0;s[i];){
        //    printf("%c
",s[i]);
            if(isdigit(s[i])||s[i]=='.'){
                temp=0,p=10;
            while(isdigit(s[i])||s[i]=='.'){
                if(s[i]=='.'){
                    p=0.1;
                    i++;
                    continue;
                }
                if(p==10)temp=temp*p+s[i]-'0';
                else temp=temp+(s[i]-'0')*p,p*=0.1;
                i++;
                }
            //    printf("%lf
",temp);
                s2.push(temp);
            }
                //s2.push(s[i++]);
            else{
                switch(work(S.top(),s[i])){
                    case '<':
                        S.push(s[i]);
                        i++;
                        break;
                    case '>':
                        a=s2.top();
                        s2.pop();
                        b=s2.top();
                        s2.pop();
                        if(S.top()=='+')
                            s2.push(a+b);
                        else if(S.top()=='-')
                            s2.push(b-a);
                        else if(S.top()=='*')
                            s2.push(a*b);
                        else s2.push(b/a);
                        //printf("%lf
",s2.top());
                        S.pop();
                        break;
                    case '=':
                        S.pop();
                        i++;
                    break;
                }
            }
        }
    //printf("%d %d %lf
",S.size(),s2.size(),s2.top());
            printf("%.2lf
",s2.top());
        }
    return 0;
}
原文地址:https://www.cnblogs.com/handsomecui/p/5236531.html