【HDU 1237】【栈】【简单计算器】

之前在网络上看到一个简单的计算器实现,结果发现是个直接根据输入的字符来进行两个数的运算,让我很失望。

每次看数据结构总是提到用栈来处理计算器,所以遇到了就直接自己手动模拟了下,感觉还好,想起来几个月前刚学编程,当时遇到一个叫我们把运算拆分的题目,我以为是写四则运算,完全没头绪,现在也能做出来了,自己总算有一丁点进步。





 #include <iostream>
    #include <cstring>
    #include <stack>
    #include <queue>
    using namespace std;
    int main(int argc, char const *argv[])
    {
        char str[1000];
        while(gets(str)!=NULL)
        {
            stack<double> num;
            stack<char> ope;
            stack<double> num2;
            stack<char> ope2;
            if(strcmp(str,"0")==0)
                return 0;
            for (int i = 0; i < strlen(str); i+=2)
            {
                if(str[i]>='0' && str[i]<='9')
                {
                    int temp=str[i]-'0';
                    while(str[i+1]<='9' && str[i+1]>='0' && (i+1)<strlen(str))
                    {
                        temp=temp*10+(str[++i]-'0');
                    }
                  //  printf("%d\n",temp);
                    num.push(temp);
                }
                else if(str[i]=='*' || str[i]=='/')
                {
                    int flag=i;
                    double a=num.top();
                    double b=str[i+2]-'0';
                    while(str[i+3]<='9' && str[i+3]>='0'&&(i+3)<strlen(str))
                    {
                        b=b*10+(str[i+3]-'0');
                        i++;
                    }
                  //  printf("%lf %lf\n",a,b);
                    num.pop();
                    if(str[flag]=='*')
                        num.push(a*b);
                    if(str[flag]=='/')
                        num.push(a/b);
                    i+=2;
                }
                else
                {
                    ope.push(str[i]);
                }
            }
            // while(!num.empty())
            // {
            //  int temp=num.top();
            //  num.pop();
            //  printf("%d\n",temp);
            // }
            // while(!ope.empty())
            // {
            //  char temp=ope.top();
            //  ope.pop();
            //  printf("%c\n",temp);
            // }
            while(num.size()!=0)
            {
                double temp=num.top();
                num.pop();
                num2.push(temp);
            }
            while(ope.size()!=0)
            {
                char temp=ope.top();
                ope.pop();
                ope2.push(temp);
            }
            while(ope2.size()!=0)
            {
                char temp=ope2.top();
                ope2.pop();
                double  b=num2.top();
                num2.pop();
                double  a=num2.top();
                num2.pop();
            //    printf("%lf %c %lf\n",b,temp,a);
                if(temp =='+')
                    num2.push(b+a);
                else
                    num2.push(b-a);
            }
            printf("%.2f\n",num2.top());
        }
        return 0;
    }


你可能感兴趣的:(c,栈)