简单计算器 hdu1237(模拟栈)

//  终于AC了。以前看到这个题目一直不知从哪里开始,学习了数据结构,才知道了方法,以前一看题目就感觉不会。
//  可是我的方法超级不好,只含+ — * /  先算乘除,然后从左往右算加减。虽然代码看上去用了,栈,其实只是用了她的思想
// 数据结构真的学的不好,接下来要好好写代码了。
#include<iostream>//2344257 2010-04-15 15:38:54 Accepted 1237 15MS 248K 1882 B C++ 悔惜晟
#include<string>
#include<cstdio>
using namespace std;

struct stack1
{
 int top;
 int base;
 double s[200];
}df1;

struct stack2
{
 int top;
 int base;
 char s[200];
}df2;

void push1 (double n)
{
 df1.s[df1.top++] = n; 
}

void push11(double n)
{
 df1.s[--df1.base] = n;
}

void pop1(double &e)
{
 e = df1.s[--df1.top];
}

void pop11(double &e)
{
 e = df1.s[df1.base++];
}

void push2 (char n)
{
 df2.s[df2.top++] = n; 
}

void pop2(char &e)
{
 e = df2.s[--df2.top];
}

void pop22(char &e)
{
 e = df2.s[df2.base++];
}

int main()
{
 char str[200];
 double sum;
 while(gets(str))
 {
  if(strcmp(str, "0") == 0)
   continue;
  int i;
  double aa = 0;
  int flag2= 0;
  int flag1 = 0;
  df1.base = 0;
  df1.top = 0;
  df2.base = 0;
  df2.top = 0;
  for(i = 0; i <= strlen(str); i++)
  {
   //if(str[i] == " ") continue;
   if(str[i] == '-' || str[i] == '+' )
   {
    push2(str[i]);
    continue;
   }
   if(str[i] == '*' || str[i] == '/' )
   {
    push2(str[i]);
    flag2 = 1;
    continue;
   }
   if(str[i] >='0' && str[i] <= '9')
   {
    aa =10 * aa + str[i] -'0';
    flag1 = 1;
    continue;
   }
   if(str[i] == '/0' || flag1 == 1 )
   {
    push1(aa);
    aa = 0;
    flag1 = 0;
    if(flag2 == 1)
    {
     double a, b;
     pop1(a);
     pop1(b);
     char e;
     pop2(e);
     if(e == '*')
     {
      sum = a * b;
      push1(sum);
     }
     else if(e == '/')
     {
      sum = b / a;
      push1(sum);
     }
     flag2 = 0;
    }
   }


  }
  while(df2.base != df2.top )//  算加减的时候从左往右
  {
   char a;
   pop22(a);
   double q, p;
   pop11(q);
   pop11(p);
   if(a == '-')
   {
    sum = q - p;
    push11(sum);
   }
   else if(a == '+')
   {
    sum = p + q;
    push11(sum);
   }

  }
  printf("%0.2lf/n", sum);
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值