简单计算器

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

***栈的使用***

分析:

例子: 4 + 2 * 5 - 7 / 11

其中每两个整数中间有一个空格,因此输入时选择先输入一个整数和一个字符(空格),后面输入的就都是一个字符串(包括一个运算符和一个空格)以及一个整数了,

输入一个整数就将对应的整数入栈,在输入的运算符为‘*’或者'/'的时候用栈顶的数字乘以或除以输入的数字(运算符的优先级)赋给变量,后将栈顶数字删除,将存

有商或者积的变量移入栈中,运算符为‘-’时,移入栈中的为-x;

AC代码:

#include<iostream>
#include<cstdio>
#include<stack>
using namespace std;
int main() {
    double temp,sum,x;
    char a[5],b;
    while (scanf("%lf%c",&x,&b))
    {
        stack<double>s;
        if (x==0&&b=='\n')
          break;
       s.push(x);
       sum=0;
       while (scanf("%s %lf",a,&x))
       {
             if (a[0]=='+')
            s.push(x);
        else if (a[0]=='-')
            s.push(-x);
        else if (a[0]=='*')
           {
               temp=s.top()*x;
               s.pop();
               s.push(temp);
           }
           else if (a[0]=='/')
           {
               temp=s.top()/x;
               s.pop();
               s.push(temp);
           }
             b=getchar();
      if (b=='\n')     //每一个计算式结束的条件
        break;
       }
    while (!s.empty())
       {
           sum+=s.top();
           s.pop();
       }
     printf("%.2lf\n",sum);
    }

    return 0;
}

posted @ 2017-07-19 20:18  你的女孩居居  阅读(276)  评论(0编辑  收藏  举报