HDU 1237 简单计算器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Datura0822/article/details/52890261

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1237

开始用栈,没弄出来,运算顺序完全不对,蠢了。

#include<cstdio>
#include<queue>
#include<cstring>
#include<iostream>
using namespace std;
int main()
{
    char s[220];
    while(gets(s),strcmp(s,"0")!=0)
    {
        queue<double>p;
        queue<char>q;
        queue<double>a;
        queue<char>b;
        for(int i=0; i<strlen(s); i++)//将字符串s的数字和符号分开存入两个队列
        {
            if(s[i]>='0'&&s[i]<='9')
            {
                int sum=s[i]-'0';
                while(s[i+1]>='0'&&s[i+1]<='9')//注意字符串中一位数字占一个字符
                {
                    sum=sum*10+(s[i+1]-'0');
                    i++;
                }
                p.push(sum);
            }
            else if(s[i]=='*'||s[i]=='/'||s[i]=='+'||s[i]=='-') q.push(s[i]);
        }
        double temp=p.front();p.pop();//第一遍算乘法和除法
        while(!q.empty())
        {
            if(q.front()=='+'||q.front()=='-') {b.push(q.front());a.push(temp);q.pop();temp=p.front();p.pop();}
            else
            {
                if(q.front()=='*') temp=temp*p.front();
                else temp=temp/p.front();
                p.pop();
                q.pop();
            }
        }
        a.push(temp);
        double ans=a.front();//第二遍算加法和减法
        a.pop();
        while(!b.empty())
        {
            if(b.front()=='+') ans=ans+a.front();
            else ans=ans-a.front();
            a.pop();
            b.pop();
        }
        printf("%.2f\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Datura0822/article/details/52890261