【算法笔记第6.6节 stack 】问题 A: 简单计算器 ( 表达式求值)

版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/xunalove/article/details/88371865

题目描述

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

输入

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

输出

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

样例输入

30 / 90 - 26 + 97 - 5 - 6 - 13 / 88 * 6 + 51 / 29 + 79 * 87 + 57 * 92
0

样例输出

12178.21

这道题目错了好几次,分析我的错误之处。

当当前遍历的运算符优先级小于等于操作符栈顶的优先级时,此时因将操作符栈顶的元素出栈,

但是一定要循环出栈到当前遍历的运算符优先级大于操作符栈顶的优先级为止。

#include<stdio.h>
#include<algorithm>
#include<iostream>
#include<stack>
#include<map>
using namespace std;
int main()
{
    stack<char> m;
    int n;
    scanf("%d",&n);
    while(n--)
    {
        string s;
        cin>>s;
        while(!m.empty())
            m.pop();
        for(int i=0; i<s.size(); i++)
        {
            if(s[i]=='}'||s[i]==']'||s[i]==')')
            {
                if(!m.empty())
                {
                    char c = m.top();
                    if((c=='('&&s[i]==')')||(c=='['&&s[i]==']')||(c=='{'&&s[i]=='}'))
                        m.pop();
                    else
                        m.push(s[i]);
                }
                else
                {
                   m.push(s[i]);
                }
            }
            else if(s[i]=='('||s[i]=='['||s[i]=='{')
                m.push(s[i]);
        }
        if(m.empty()==1)
            cout<<"yes"<<endl;
        else
            cout<<"no"<<endl;
    }
}
 
/**************************************************************
    Problem: 1982
    User: 151210132
    Language: C++
    Result: 正确
    Time:0 ms
    Memory:2020 kb
****************************************************************/

猜你喜欢

转载自blog.csdn.net/xunalove/article/details/88371865