成绩 | 10 | 开启时间 | 2017年11月24日 星期五 00:00 |
折扣 | 0.8 | 折扣时间 | 2017年12月18日 星期一 00:00 |
允许迟交 | 否 | 关闭时间 | 2017年12月31日 星期日 00:00 |
题目:给定后缀表达式,计算出该式的值。为简单起见,用于计算的数字均在0-9之间。
输入:
某个四则运算式的后缀表达式,其中除法"/"简化为整除。
输出:
该四则运算式的计算结果。若后缀表达式不合法,输出“ERROR!";若计算过程中有除以0的情况,输出"DIV0!"
#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;
}