【id:57】【15分】E. DS堆栈--表达式计算

输入样例

#号为表达式结尾

2
1+2*3-4/5#
(66+(((11+22)*2-33)/3+6)*2)-45.6789#

输出样例

保留4位小数

6.2000
54.3211

answer

#include<iostream>
#include<iomanip>
#include<stack>
#include<map>
#include<cstdlib>
#include<string>
using namespace std;
map<char,int>m = {
    {'(', 0},
    {'+', 1},
    {'-', 1},
    {'*', 2},
    {'/', 2},
};
double calculate(double n1, double n2, char ch){
    if(ch=='+')return n1+n2;
    else if(ch=='-')return n1-n2;
    else if(ch=='*')return n1*n2;
    else if(ch=='/')return n1/n2;
}
void calculate_process(stack<double>& num_stk, stack<char>&ch_stk){
    double n2=num_stk.top();
    num_stk.pop();
    double n1=num_stk.top();
    num_stk.pop();
    char ch=ch_stk.top();
    ch_stk.pop();
    double num = calculate(n1, n2, ch);
    num_stk.push(num);
}
int main(){
    int n;
    cin>>n;
    for(int i=0; i<n; i++){
        string s;
        cin>>s;
        stack<double>num_stk;
        stack<char>ch_stk;
        for(int j=0; j<s.size()-1; j++){
            if(s[j] >= '0' && s[j] <= '9'){
                int c=j;
                while((s[c] >= '0' && s[c] <= '9')||s[c]=='.'){
                    c++;
                }
                c=c-j;
                num_stk.push(atof(s.substr(j,c).c_str()));
                j+=(c-1);
            }
            else if(ch_stk.empty() || s[j]=='(' || m[s[j]]>m[ch_stk.top()]){
                ch_stk.push(s[j]);
            }
            else if(s[j]==')'){
                while(ch_stk.top()!='('){
                    calculate_process(num_stk, ch_stk);
                }
                ch_stk.pop();
            }
            else{
                while(!ch_stk.empty()&&m[s[j]]<=m[ch_stk.top()]){
                    calculate_process(num_stk, ch_stk);
                }
                ch_stk.push(s[j]);
            }
        }
        while(!ch_stk.empty()){
            calculate_process(num_stk, ch_stk);
        }
        cout<<fixed<<setprecision(4)<<num_stk.top()<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值