前缀表达式计算(栈的使用)

#include <bits/stdc++.h>
using namespace std;
string s;
stack<double>ac;
bool op(char c){
    if(c=='+'||c=='-'||c=='*'||c=='/'){
        return 1;
    }
    else return 0;
}
int main(){
        getline(cin,s);
        while(!ac.empty()){
            ac.pop();
        }
        int len=s.length();
        int n=1;
        double num=0;
        int flag=0;
        for(int i=len-1;i>=0;i--){
            if(s[i]>='0'&&s[i]<='9'){
                num+=(s[i]-'0')*n;
                n*=10;
            }
            else if(s[i]=='.'){
                num=num/(n*1.0);
                n=1;
            }
            else if((s[i]=='+'||s[i]=='-')&&num!=0){
                if(s[i]=='+'){
                    ac.push(num);
                    i--;
                    continue;
                }
                else{
                    num=-num;
                    ac.push(num);
                    i--;
                    continue;
                }
            }
            else if(s[i]==' '){
                ac.push(num);
                num=0;
                n=1;
                continue;
            }
            else if(op(s[i])){
                double a=ac.top();
                ac.pop();
                double b=ac.top();
                ac.pop();
                double t=0;
                if(s[i]=='+'){
                    t=a+b;
                }
                else if(s[i]=='-'){
                    t=a-b;
                }
                else if(s[i]=='*'){
                    t=a*b;
                }
                else if(s[i]=='/'){
                    if(b==0){
                        flag=1;
                        break;
                    }
                    t=a/b;
                }
                ac.push(t);
                i--;
            }
        }
        if(flag==0){
            printf("%.1f\n",ac.top());
        }
        else{
            printf("ERROR\n");
        }
    return 0;
}

posted @ 2020-02-29 14:31  lhl1020  阅读(552)  评论(1编辑  收藏  举报