HDU 1237 简单计算器 (栈模拟)

#include <stack>
#include <cstdio>
using namespace std;
const int maxn =200+5;
char s[maxn];
//考虑到 1 - 2 + 2 / 1 = 1.00 的特殊性,将减法转换为加法
int main()
{
    while(gets(s)!=NULL)
    {
        int L=strlen(s);
        if(L==1&&s[0]=='0') break;//仅有1个0时结束循环
        stack<double>q;//数字栈
        stack<char>v;//符号栈
        bool flag=true;//判断当前数字的正负
        double c=0,y;
        for(int i=0; s[i];)
            if(s[i]>='0'&&s[i]<='9')
            {
                c=c*10+s[i]-'0';
                i++;
            }
            else if(s[i]=='+'||s[i]=='-')//每次遇到+,-号直接将c进栈
            {
                if(!flag) q.push(-1*c);//前一个数字为负,下同
                else q.push(c);
                if(s[i]=='-') flag=false;
                else flag=true;
                c=0;
                v.push(s[i]),i++;
            }
            else if(s[i]!=' ')
            {
                char tt=s[i];
                i+=2;
                y=0;
                while(s[i]>='0'&&s[i]<='9'&&i<L) y=y*10+s[i]-'0',i++;//读取下一个数字
                if(tt=='*') c*=y;
                else c/=y;
            }
            else i++;
        //将末尾的运算结果进栈
        if(!flag) q.push(-1*c);
        else q.push(c);
        while(!v.empty())//符号出栈进行加法运算
        {
            char tt=v.top();
            v.pop();
            double x=q.top();
            q.pop();
            double y=q.top();
            q.pop();
            y+=x;
            q.push(y);
        }
        printf("%.2lf\n",q.top());
    }
    return 0;
}


你可能感兴趣的:(HDU 1237 简单计算器 (栈模拟))