将一个算术表达式(即中缀形式)转化成其后缀形式,并算出答案。
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <stack>
#include <algorithm>
#include <stdlib.h>
using namespace std;
using namespace std;
bool IsOperator(char ch)
{
char ops[] = "+-*/";
for (int i = 0; i < sizeof(ops) / sizeof(char); i++)
{
if (ch == ops[i])
return true;
}
return false;
}
// 比较两个操作符的优先级
int Precedence(char op1, char op2)
{
if (op1 == '(')
{
return -1;
}
if (op1 == '+' || op1 == '-')
{
if (op2 == '*' || op2 == '/')
{
return -1;
}
else
{
return 0;
}
}
if (op1 == '*' || op1 == '/')
{
if (op2 == '+' || op2 == '-')
{
return 1;
}
else
{
return 0;
}
}
}
// 中缀表达式转换成后缀表达式
void inFix2PostFix(char* inFix, char* postFix)
{
int j = 0, len;
char c;
stack<char> st;
len = strlen(inFix);
for (int i = 0; i < len; i++)
{
c = inFix[i];
if (c == '(') st.push(c);//左括号 入栈
else if (c == ')')//右括号 寻找栈内的左括号 弹出左右括号
{
while (st.top() != '(')
{
postFix[j++] = st.top();
st.pop();
}
st.pop();
}
else
{
if (!IsOperator(c)) st.push(c);
else
{
while (!st.empty() && Precedence(st.top(), c) >= 0)//入栈元素优先级不高于栈顶元素
{
postFix[j++] = st.top();//记下栈顶元素
st.pop();//栈顶元素出栈
}
st.push(c);//入栈元素入栈
}
}
}
while (!st.empty())//依次标记 出栈
{
postFix[j++] = st.top();
st.pop();
}
postFix[j] = 0;
}
// 后缀表达式求值程序
double postFixEval(char* postFix)
{
stack<int> st;
int len = strlen(postFix);
char c;
for (int i = 0; i < len; i++)
{
c = postFix[i];
if (IsOperator(c) == false)
{
int tmp=c-'0';
st.push(tmp);//字符变数字
}
else
{
int op1, op2;
int val;
op1 = st.top();
st.pop();
op2 = st.top();//取栈顶两数
st.pop();
switch (c)//运算
{
case '+':
val = op1 + op2;
break;
case '-':
val = op2 - op1;
break;
case '*':
val = op1 * op2;
break;
case '/':
val = op2 / op1;
break;
}
st.push(val);
}
}
return st.top();
}
int main()
{
char inFix[100];
char postFix[100];
double val;
while (1)
{
printf("enter an expression: ");
gets(inFix);
if (strlen(inFix) == 0)
continue;
printf("\n%s = ", inFix);
inFix2PostFix(inFix, postFix);
printf("%s = ", postFix);
val = postFixEval(postFix);
printf("%.3f\n", val);
}
return 0;
}