sicily 后缀表达式计算

WA了无数次心都碎了,一直改到3点多才交上的= =感觉思想很简单,使用了一个栈。依次遍历字符串,若为字幕的话,则将其push到栈中,若为运算符号,则将栈顶元素与下一个元素进行运算,然后将运算的结果push进去栈中。。依次执行这些操作即可。

代码如下:

#include<iostream>
#include<iomanip>
#include<string>
#include<stack>
using namespace std;
int main() {
    int n;
    string s;
    cin>>n;
    while (n--) {   
        cin>>s;
        stack<double>table;
        double num = 0, temp, temp1;
        for (int i = 0 ; i < s.size() ; i++) {
            if (s[i]>=97 && s[i]<=122)
                table.push(s[i]-96); // 根据asc码来的
            else {
                temp = table.top();  // 将栈顶元素设为temp,并将其pop掉,然后计算temp和当前的栈顶元素
                table.pop();
                temp1 = table.top();
                table.pop();
                if (s[i] ==43) {
                    num = temp + temp1;
                    table.push(num);
                }
                else if (s[i] ==45) {
                    num = temp1 - temp;
                    table.push(num);
                }
                 else if (s[i] == 42) {
                    num =  temp * temp1;
                    table.push(num);
                }
                else if (s[i] ==47) {
                    num = temp1 / temp;
                    table.push(num);
                }
            }
        }
        cout <<fixed <<setprecision(2) <<num <<endl; // C++保留两位小数的方法,记得头文件要写#include<iomanip>
    }
    return 0;
}                                 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值