主要利用栈和队列实现简单的计算器功能,保证正确的运算顺序:
步骤一:将中缀表达式转换为后缀表达式

步骤二:计算后缀表达式

#include<cstdio>
#include<cmath>
#include<cstring>
#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<string>
#include<stack>
#include<queue>
#include<map>
#define MAX 100010

using namespace std;
struct node{
    double num;//操作数
    char op;//操作符
    bool flag;//true表示操作数,false表示操作符
};
string str;
stack<node> s;
queue<node> q;
map<char,int> op;
//指明优先级
//中缀表达式转换为后缀表达式
void Change(){
    double num;
    node temp;
    for(int i=0;i<str.length();){
        if(str[i]>='0'&&str[i]<='9'){
            temp.flag=true;
            temp.num=str[i++]-'0';
            while(i<str.length()&&str[i]>='0'&&str[i]<='9'){
                temp.num=temp.num*10+(str[i++]-'0');
            }
            q.push(temp);
        }
        else{
            temp.flag=false;
            //只要操作符栈的栈顶元素比该操作符优先级高,
            //就把操作符栈顶元素弹出到后缀表达式的队列中
            while(!s.empty()&&op[str[i]]<=op[s.top().op]){
                q.push(s.top());
                s.pop();
            }
            temp.op=str[i++];
            s.push(temp);
        }
    }
    //如果操作符栈中还有操作符,就弹出到后缀表达式中
    while(!s.empty()){
        q.push(s.top());
        s.pop();
    }
}
double Cal_latter(){
    node q_front,temp;
    double temp1,temp2;
    while(!q.empty()){
        q_front=q.front();
        q.pop();
        if(q_front.flag==true) s.push(q_front);
        else{//操作符
            temp2=s.top().num;
            s.pop();
            temp1=s.top().num;
            s.pop();
            temp.flag=true;
            if(q_front.op=='+') temp.num=temp1+temp2;
            else if(q_front.op=='-') temp.num=temp1-temp2;
            else if(q_front.op=='*') temp.num=temp1*temp2;
            else temp.num=temp1/temp2;
            s.push(temp);
        }
    }
    return s.top().num;
}
int main(){

    op['+']=op['-']=1;
    op['*']=op['/']=2;
    while(getline(cin,str),str!="0"){
        for(string::iterator it=str.end();it!=str.begin();it--){
            if(*it==' ') str.erase(it);//去除表达式的空格
        }
        while(!s.empty()) s.pop();//初始化栈
        Change();
        printf("%.2f\n",Cal_latter());
    }
    return 0;
}

 

posted on 2018-04-02 11:45  Sunshine&暖阳  阅读(85)  评论(0编辑  收藏  举报