ACM: 简单计算器

一、题目大意

在这里插入图片描述

二、题目思路

维护一个运算符栈,维护一个数字栈. 当当前输入运算符优先级小于等于当前运算符栈的运算符时,进行栈顶运算符的运算,为了编码方便,引入一个最低优先级的运算符$. 一些值得注意的小细节。

  • 数字可能是多位数的
  • 使用stringstream作为字符串流输入进行输入

三、代码

#include<iostream>
#include<stack>
#include<sstream>
#include<stdio.h>
using namespace std;

int el[5][5]={
0,1,1,1,1,
0,1,1,1,1,
0,1,1,1,1,
0,0,0,1,1,
0,0,0,1,1,
};

char ch;
int op2id[100];

stack<int> op;
stack<double> num;
int main()
{
    op2id['+'] = 1;
    op2id['-'] = 2;
    op2id['*'] = 3;
    op2id['/'] = 4;
    op2id['$'] = 0;
    string line;
    while(getline(cin, line))
    {
        if(line == "0")
            break;
        while(!op.empty())
            op.pop();
        while(!num.empty())
            num.pop();
        line = line + " $";
        op.push(0);
        stringstream inputs(line);
        string s;
        while(inputs >> s)
        {
            if(s.length() > 1)
            {
                double temp = 0;
                for(int i=0; i<s.length(); i++)
                    temp = temp * 10 + s[i] - '0';
                num.push(temp);
                continue;
            }

            ch = s[0];
            if(isdigit(ch))
                num.push((ch - '0')*1.0);
            else
            {
                int top = op.top();
                while(el[op2id[ch]][top])
                {
                    double a = num.top(); num.pop();
                    double b = num.top(); num.pop();
                    if(top == 1)
                        num.push(a+b);
                    else if(top == 2)
                        num.push(b-a);
                    else if(top == 3)
                        num.push(b*a);
                    else
                        num.push(b/a);
                    op.pop();
                    top = op.top();
                }
                op.push(op2id[ch]);
            }
        }

        printf("%.2lf\n", num.top());
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值