4.已知运算式判断合法性及求值

成绩 10 开启时间 2017年11月24日 星期五 00:00
折扣 0.8 折扣时间 2017年12月18日 星期一 00:00
允许迟交 关闭时间 2017年12月31日 星期日 00:00

题目:给定后缀表达式,计算出该式的值。为简单起见,用于计算的数字均在0-9之间。

输入:

某个四则运算式的后缀表达式,其中除法"/"简化为整除。

输出:

该四则运算式的计算结果。若后缀表达式不合法,输出“ERROR!";若计算过程中有除以0的情况,输出"DIV0!"

  测试输入关于“测试输入”的帮助 期待的输出关于“期待的输出”的帮助 时间限制关于“时间限制”的帮助 内存限制关于“内存限制”的帮助 额外进程关于“{$a} 个额外进程”的帮助
测试用例 1 以文本方式显示
  1. 11+↵
以文本方式显示
  1. 2↵
1秒 64M 0

#include<cstdio> 
#include<string> 
#include<map> 
#include<stack> 
#include<math.h> 
#include<iostream> 
using namespace std; 
 
stack<char> Op; 
stack<int>  Opnum; 
string Instruction; 
int GetproiIncoming(char c) 
{ 
 switch (c) 
 { 
  case('+') : return 3; 
  case('-') : return 3; 
  case('*') : return 5; 
  case('/') : return 5; 
  //case('%') : return 5; 
    //case('(') : return 10; 
   //case('^') : return 8; 
    } 
} 
 
int GetproInstack(char c) 
{ 
   switch (c) 
 { 
  case('+') : return 4; 
  case('-') : return 4; 
  case('*') : return 6; 
  case('/') : return 6; 
  //case('%') : return 6; 
    //case('(') : return 1; 
    //case('^') : return 7; 
    } 
} 
int Comput(char c, int a, int b) 
{ 
 switch (c) 
 { 
  case('+') : return a + b; 
  case('-') : return a - b; 
  case('*') : return a*b; 
    case('/') : return a / b; 
  //case('%') : return a%b; 
  //case('^') : return (int)pow(double(a), double(b)); 
   } 
} 
 
void getresult(string Instruction) 
{ 
  for (int i = 0; Instruction[i]; i++) 
   { 
      if (Instruction[i] >= '0'&&Instruction[i] <= '9') 
        { 
          int num = Instruction[i] - '0'; 
            Opnum.push(num); 
       } 
      else 
       { 
          if (Opnum.size() < 2) 
           { 
              printf("ERROR!\n"); 
                return; 
            } 
          else 
           { 
              int a = Opnum.top(); Opnum.pop(); 
              int b = Opnum.top(); Opnum.pop(); 
              if (Instruction[i] == '/'&&a == 0) 
             { 
                  printf("DIV0!\n"); 
                 return; 
                } 
              int num = Comput(Instruction[i], b, a); 
                Opnum.push(num); 
           } 
      } 
  } 
  if (Opnum.size() > 1) 
   { 
      printf("ERROR!\n"); 
        return; 
    } 
  printf("%d\n",Opnum.top()); 
} 
int main() 
{ 
 getline(cin, Instruction); 
  getresult(Instruction); 
   return 0; 
}  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水之积也不厚,则其负大舟也无力

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值