中缀表达式转逆波兰式并计算

#include<cstdio>
#include<algorithm>
#include<iostream>
#include<vector>
#include<cstring>
#include<stack>
#include<queue>
#include<string>
#include<map>
using namespace std;
//对于输入串,处理分离出数字串,将其转换成数字,分离运算符,
//中缀转后缀 若当前处理的单位是数字,将其入队(字符串队列),如果是运算符若栈<字符栈>当前为空或者栈顶运算符
//优先级比其低则入栈,若栈顶运算符优先级比其高或等于,则栈顶一直出栈直到栈顶运算符优先级比其低
//后缀表达式中位置处于右边的运算符后运算,即优先级低,相同优先级的按从左到右的优先级来处理
//例如对于a+b*c/d,abc*d/+
//逆波兰式队列中存的是字符串
//计算逆波兰式,从左到右遍历该串,是数字则入栈<数字栈>,是运算符则取出栈两个元素运算,并将结果入栈,直到扫描
//结束,此时栈顶元素即为结果
//字符串转整数函数<double型>
stack<char>s1;
stack<double>s2;
queue<string>q;
string str;
map<char,int>m1;
void tosuffix()
{
    
    
    int i=0;
    string temp;
    while(i<str.length()){
    
    
    if('0'<=str[i]&&str[i]<='9'){
    
    
        temp.clear();
        while(str[i]!=' '&&str[i]){
    
    
            temp+=str[i];
            i++;
        }
        q.push(temp);
    }
    else if(str[i]!=' '){
    
    
        if(s1.empty()||m1[s1.top()]<m1[str[i]]){
    
    
            s1.push(str[i]);
        }
        else{
    
    
            while(!s1.empty()&&m1[s1.top()]>=m1[str[i]]){
    
    
                string temp;
                temp+=s1.top();
                q.push(temp);
                s1.pop();
            }
            s1.push(str[i]);
        }
        i++;
    }
    i++;
    }
    while(!s1.empty()){
    
    
        string temp;
        temp+=s1.top();
        q.push(temp);
        s1.pop();
    }
}
void read(string& str)
{
    
    
    char c;
    while(scanf("%c",&c),c!='\n'){
    
    
        str+=c;
    }
}
void fun(string str)//转换成double并入栈
{
    
    
    double sum=0;
    for(int i=0;i<str.size();i++){
    
    
        sum=sum*10+(str[i]-'0');//万年错误终于被找出来了,之前是sum+=sum*10+(str[i]-'0')
    }
    s2.push(sum);
}
void process(char x)
{
    
    
    double a,b;
    b=s2.top();
    s2.pop();
    a=s2.top();
    s2.pop();
    if(x=='+'){
    
    
        s2.push(a+b);
    }
    else if(x=='-'){
    
    
        s2.push(a-b);
    }
    else if(x=='*'){
    
    
        s2.push(a*b);
    }
    else if(x=='/'){
    
    
        s2.push(a/b);
    }
}
int main()
{
    
    
    m1['+']=1;
    m1['-']=1;
    m1['*']=2;
    m1['/']=2;
    while(getline(cin,str),str!="0"){
    
    
        while(!s2.empty()){
    
    
            s2.pop();
        }
        while(!s1.empty()){
    
    
            s1.pop();
        }
        while(!q.empty()){
    
    
            q.pop();
        }
        //read(str);之前的输入放在codeup评判会超时
        //if(str[0]=='0'&&str.length()==1){
    
    
        //    break;
        //}
        tosuffix();
        while(!q.empty()){
    
    
            if('0'<=q.front()[0]&&q.front()[0]<='9'){
    
    
                fun(q.front());
            }
            else{
    
    
                process(q.front()[0]);
            }
            q.pop();
        }
        printf("%.2f\n",s2.top());
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45890608/article/details/111628826