zoukankan      html  css  js  c++  java
  • 简单计算器

    题目链接: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==' ')
              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==' ')     //每一个计算式结束的条件
            break;
           }
        while (!s.empty())
           {
               sum+=s.top();
               s.pop();
           }
         printf("%.2lf ",sum);
        }

        return 0;
    }

  • 相关阅读:
    浏览器同源政策及其规避方法---转阮大神
    js跨域详解
    js中top、self、parent
    杂记
    DOM 踩踩踩
    java idea 连接数据库
    数据库mySQL常用命令
    用迭代实现80人围成一圈逢3取出
    如何把通过类建立的对象存入数组中.
    面向对象编程
  • 原文地址:https://www.cnblogs.com/lisijie/p/7207681.html
Copyright © 2011-2022 走看看