数据结构—表达式求值

 

在这里插入图片描述

#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;
}
posted @ 2018-10-30 13:33  Nlifea  阅读(281)  评论(0编辑  收藏  举报