九度1019解题报告

关于计算器的题目http://ac.jobdu.com/problem.php?pid=1019,该题要编写的计算器比一般的计算器简单,因为不含括号,运算优先级就两种,先算乘除法就好,这是受到了fripSide同学的启发,不需要算术符号栈,只需要数字栈,遇加减号就将下一个数字入栈(遇减号将数字反号入栈),遇乘除号,就将栈顶的数字取出运算后再入栈。当处理完整个计算式时,将栈中的所有数取出相加,既得结果。代码如下

#include <stdio.h>
#include <stack>
#include <string.h>
using namespace std;

stack <double> num;

int main()
{
    double a;
    char b;
    while (scanf("%lf",&a)!=EOF&&a!=0)
    {
        while (!num.empty()) num.pop();
        num.push(a);
            while (scanf("%c", &b)!=EOF)
            {
                  while (b==' ') b=getchar();
                  if (b=='\n') break;
                  scanf("%lf",&a);
                  if (b=='+') num.push(a);
                  if (b=='-') num.push(-a);
                  if (b=='*')
                  {
                      double temp1=a*num.top();
                      num.pop();
                      num.push(temp1);       
                  }
                  if (b=='/')
                  {
                      double temp2=num.top()/a;
                      num.pop();
                      num.push(temp2);       
                  }
            }       
        double ans=0;
        while (!num.empty())
        {
            ans+=num.top();
            num.pop();  
        }
        printf("%.2lf\n",ans);
    }
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值