题解 | #计算表达式#

计算表达式

https://www.nowcoder.com/practice/7b18aa6b7cc14f8eaae6b8acdebf890b

//stack应用:表达式求值
//无括号四则运算通用模版
#include <iostream>
#include <cctype>//isdigit(str[index])
#include <stack>
using namespace std;

double GetNumber(string str,int& index)
{
    double number=0;
    while(isdigit(str[index]))
    {
        number=number*10+str[index]-'0';
        index++;
    }
    return number;
}
int Prior(char op)
{
    if(op=='#')return 0;
    else if(op=='$')return 1;
    else if(op=='+'||op=='-')return 2;
    else return 3;
}
double Calculate(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 result=x/y;
    return result; 
}
int main() {
    string str;
    while (getline(cin,str)) {
        if(str==" ")break;
        int index=0;
        stack<double> num;
        stack<char> oper;
        oper.push('#');//优先级最小
        str+='$';///有必要 因为当栈内剩下最后一个+/*-运算符时,需要$来将其预算掉
        while(index<str.size())
        {
            if(isdigit(str[index]))
            {
                num.push(GetNumber(str,index));
            }
            else if(Prior(oper.top())<Prior(str[index]))
            {
                oper.push(str[index]);
                index++;
            }
            else {
                double y=num.top();
                num.pop();
                double x=num.top();
                num.pop();
                num.push(Calculate(x,y,oper.top()));
                oper.pop();
            }
        }
        cout<<num.top()<<endl;

    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
06-02 15:17
门头沟学院 Java
心爱的idea:怎么会呢 应该是打招呼有问题 问就说实习6个月全国可飞随时到岗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务