逆波兰式与表达式求解

/***************
逆波兰式即后缀表示法
  预处理 ———— 中序表达式 - > 逆序表达式(infix to postfix)
	算法:
	while (表达式非空)
		if (遇到操作数)
			直接输出
		else if (遇到操作符op)
			op是(直接入栈s
			op是) s.push输出,直到(
			op是四则运算,则
				while (1)
					if (s为空 || s.top为(|| op 优先级高于 s.top)
						op 入栈
						break;
					else
						s.push输出
	while (!s.empty)
		s.push输出
计算
	算法 :
	if (遇到操作数)
		入栈s
	else (遇到操作符)
	        s.push两个元素进行运算,结果入栈
*******************/
#include <iostream>
#include <stack>
#include <cstring>
#include <string>
#include <cstdio>
using namespace std;

stack<char> op_flag;
stack<double> result;
double Result(char *s)
{
	double tmp, a, b;
	while ('\0' != *s)
	{
		if (*s >= '0' && *s <= '9' || '.' == *s)
		{
			sscanf(s, "%lf", &tmp);
			while (*s >= '0' && *s <= '9' || '.' == *s)
				++s;
			result.push(tmp);
		}
		else if (NULL != strchr("+/-*", *s))
		{
			b = result.top();
			result.pop();
			a = result.top();
			result.pop();
			if ('+' == *s)
				result.push(a + b);
			else if ('-' == *s)
				result.push(a - b);
			else if ('*' == *s)
				result.push(a*b);
			else if ('/' == *s)
				result.push(a / b);
			++s;
		}
		else
			++s;
	}
	return result.top();
}
void Get_after(char *s, char *re)
{
	while ('\0' != *s)
	{
		if (NULL != strchr("0123456789.", *s))
		{
			*re++ = *s;
		}
		else
		{
			if ('(' == *s)
			{
				op_flag.push((char)*s);
			}
			else if (')' == *s)
			{
				while ('(' != op_flag.top())
				{
					*re++ = ' ';
					*re++ = op_flag.top();
					op_flag.pop();
				}
				op_flag.pop();
			}
			else if (NULL != strchr("*-+/", *s))
			{
				while (1)
				{
					*re++ = ' ';
					if (op_flag.empty() || '(' == op_flag.top()
						|| (NULL != strchr("+-", op_flag.top()) && NULL != strchr("*/", *s)))
					{
						op_flag.push((char)*s);
						break;
					}
					else
					{
						*re++ = op_flag.top();
						op_flag.pop();
					}
				}
			}
		}
		s++;
	}
	while (!op_flag.empty())
	{
		*re++ = ' ';
		*re++ = op_flag.top();
		op_flag.pop();
	}
	*re = '\0';
}
int main()
{
	char s[1000], re[1000];
	printf("本计算器支持四则运算和括号以及小数运算,请输入正确表达式,以防崩溃\n");
	while (1)
	{
		while (!op_flag.empty())
			op_flag.pop();
		while (!result.empty())
			result.pop();
		printf("输入表达式:");
		gets(s);
		Get_after(s, re);
		printf("结果:%.2lf\n", Result(re));
	}
	return 0;
}

你可能感兴趣的:(逆波兰式,后序表达式,表达式求解,中序表达式,波兰式)