#include<iostream>
#include<cstring>
#include<cstdio>
#include<cctype>
#include<stack>
using namespace std;
stack<char> opter;
stack<double> opval;
int getIndex(char theta)
{
int index = 0;
switch (theta)
{
case '+':
index = 0;
break;
case '-':
index = 1;
break;
case '*':
index = 2;
break;
case '/':
index = 3;
break;
case '(':
index = 4;
break;
case ')':
index = 5;
break;
case '#':
index = 6;
default:
break;
}
return index;
}
char getPriority(char theta1, char theta2)
{
const char priority[][7] =
{
{ '>','>','<','<','<','>','>' },
{ '>','>','<','<','<','>','>' },
{ '>','>','>','>','<','>','>' },
{ '>','>','>','>','<','>','>' },
{ '<','<','<','<','<','=','0' },
{ '>','>','>','>','0','>','>' },
{ '<','<','<','<','<','0','=' },
};
int index1 = getIndex(theta1);
int index2 = getIndex(theta2);
return priority[index1][index2];
}
double calculate(double b, char theta, double a)
{
switch (theta)
{
case '+':
return b + a;
case '-':
return b - a;
case '*':
return b * a;
case '/':
return b / a;
default:
break;
}
}
double getAnswer()
{
opter.push('#');
int counter = 0;
char c = getchar();
while (c != '#' || opter.top() != '#') {
if (isdigit(c)) {
if (counter == 1) {
double t = opval.top();
opval.pop();
opval.push(t * 10 + (c - '0'));
counter = 1;
} else {
opval.push(c - '0');
counter++;
}
c = getchar();
} else {
counter = 0;
switch (getPriority(opter.top(), c)) {
case '<': //<则将c入栈opter
opter.push(c);
c = getchar();
break;
case '=': //=将opter栈顶元素弹出,用于括号的处理
opter.pop();
c = getchar();
break;
case '>': //>则计算
char theta = opter.top();
opter.pop();
double a = opval.top();
opval.pop();
double b = opval.top();
opval.pop();
opval.push(calculate(b, theta, a));
}
}
}
return opval.top();
}
int main() {
int t;
cin >> t;
getchar();
while (t--) {
while ( !opter.empty() ) opter.pop();
while ( !opval.empty() ) opval.pop();
double ans = getAnswer();
cout << ans << endl << endl ;
getchar();
}
return 0;
}
数据结构—表达式求值
最新推荐文章于 2024-08-22 11:21:46 发布