KY102 计算表达式

阅读 63

2022-01-20

描述

对于一个不存在括号的表达式进行计算

输入描述:

存在多种数据,每组数据一行,表达式不存在空格

输出描述:

输出结果

示例1

输入:

6/2+3+3*4

输出:

18
代码示例:

#include<iostream>
#include<string>
#include<cmath>
#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 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(cin>>str)
    {
        stack<char>oper;
        stack<double>data;
        str+='$';
        oper.push('#');
        int index=0;
        while(index<str.size())
        {
            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();
                    double x=data.top();
                    data.pop();
                    data.push(Calculate(x,y,oper.top()));
                    oper.pop();
                }
            }
        }
        cout<<data.top()<<endl;
    }
    return 0;
}

精彩评论(0)

0 0 举报