【栈】问题 A: 简单计算器

题目描述

读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。

输入

测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。

输出

对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。

样例输入 复制
30 / 90 - 26 + 97 - 5 - 6 - 13 / 88 * 6 + 51 / 29 + 79 * 87 + 57 * 92
0
样例输出 复制
12178.21
分析:

利用两个栈一个映射来模拟中序表达式的计算以及运算符的优先级,第一个栈存储操作数,第二个栈存储运算符。

不断判断读入字符是数字还是操作符,若是数字则存储起来,直到不是数字时压入操作数栈;若是运算符则判断运算符栈是否为空,为空就压入栈,不为空则不断读出栈顶的操作符,判断两者的优先级,若大于等于则弹出运算符和两个操作数,进行运算,并将结果压入操作数栈,直到操作数栈为空或者前者优先级小于后者。

读完字符后,若运算符栈不为空,则不断读取,并按之前的方式运算,直到运算符栈为空。

要点:
  1. 操作数压入栈的时机除了读入非数字的时候,还有最后字符读完的时候,因为此时字符已读完,但之前的数字未压入。

  1. 当读入运算符且栈为空时,若栈顶的运算符优先级大于等于当前的,还要再次循环,这是因为当运算符优先级相同时,总是从左往右的。

#include <iostream>
#include <string>
#include <stack>
#include <cctype>
#include <map>

using namespace std;

double opera(double n1, double n2, char op);

int main()
{
    string s;
    map<char, int> mp;
    mp['+'] = 1, mp['-'] = 1, mp['*'] = 2, mp['/'] = 2;
    while(getline(cin, s) && s != "0"){
        double num = 0;
        stack<char> op;
        stack<double> n;
        for(int i = 0; i < s.length(); i++){
            if(isdigit(s[i])){
                num *= 10;
                num += s[i] - '0';
            }
            if((i + 1 == s.length())){
                n.push(num);
                num = 0;
            }
            if(s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/'){
                n.push(num);
                num = 0;
                if(!op.empty()){
                    while(!op.empty() && mp[op.top()] >= mp[s[i]]){
                        char past = op.top();
                        op.pop();
                        double n2 = n.top();
                        n.pop();
                        double n1 = n.top();
                        n.pop();
                        num = opera(n1, n2, past);
                        n.push(num);
                        num = 0;
                    }
                }
                op.push(s[i]);
            }
        }
        while(!op.empty()){
            char past = op.top();
            op.pop();
            double n2 = n.top();
            n.pop();
            double n1 = n.top();
            n.pop();
            num = opera(n1, n2, past);
            n.push(num);
        }
        num = n.top();
        cout << fixed, cout.precision(2);
        cout << num << '\n';
    }
    return 0;
}
double opera(double n1, double n2, char op){
    double result;
    switch(op){
        case '+':result = n1 + n2;return result;
        case '-':result = n1 - n2;return result;
        case '*':result = n1 * n2;return result;
        case '/':result = n1 / n2;return result;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值