栈的应用——简单运算器

简单计算器

https://www.nowcoder.com/practice/5759c29a28cb4361bc3605979d5a6130?tpId=40&&tqId=21460&rp=1&ru=/ta/kaoyan&qru=/ta/kaoyan/question-ranking

#include <iostream>
#include <cstdio>
#include <cctype>
#include <string>
#include <stack>
   
using namespace std;

int Priority(char c){        //优先级 #,¥,+-,*/
    if(c=='#')
        return 0;
    else if(c=='$')
        return 1;
    else if(c=='+'||c=='-')
        return 2;
    else
        return 3;
}

double GetNumber(string str,int& index){        //字符串中获得下一个数字
    double number=0;
    while(isdigit(str[index])){
        number = number*10 + str[index]-'0';
        index++;
    }
    return number;
}

double Caculate(double x,double y,char op){
    double result=0;
    if(op=='+')
        result=x+y;
    else if(op=='-')
        result=x-y;
    else if(op=='*')
        result=x*y;
    else if(op=='/')
        result=x/y;
    return result;
}

int main(){
    string str;
    while(getline(cin, str)){
        if(str == "0")
            break;
        int index=0;            //字符串下表
        stack<char> oper;
        stack<double> data;
        str +='$';                //字符串尾部添加$
        oper.push('#');            //运算字符串底部添加#
        while(index<str.size()){
            if(str[index]==' ')
                index++;
            else if(isdigit(str[index]))             //得到字符串中数字
                data.push(GetNumber(str,index));
            else{
                if(Priority(oper.top()) < Priority(str[index])){
                    oper.push(str[index]);
                    index++;
                }    //字符串中后续操作符优先级高于操作符栈顶优先级,直接入操作符栈
                    
              else{                                //否则就符合情况中间运算符可以优先运算了
                    double y=data.top();
                    data.pop();                    //用完数字就将数字pop掉
                    double x=data.top();
                    data.pop();
                    data.push(Caculate(x,y,oper.top()));    //由于考虑到-和/,现出来为第二项y
                    oper.pop();        //使用完成后,所使用的栈顶运算符pop出
                }
            }
        }
        printf("%.2f\n",data.top());
    }
    return 0;
}
全部评论

相关推荐

头像
不愿透露姓名的神秘牛友
04-29 09:17
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务