中缀表达式求值
通过把“中缀转后缀”和“后缀求值”两个算法功能集成在一起(非简单的顺序调用),实现对中缀表达式直接求值,新算法还是从左到右扫描中缀表达式,但同时使用两个栈,一个暂存操作符,一个暂存操作数,来进行求值。(支持 + - * / ^ 五种运算)
输入样例:
( 2 + 3 ) * 6 + 4 / 2
输出样例:
32
#include <iostream>
#include <string>
#include <cstring>
#include <cmath>
using namespace std;
stack< int > operant;
stack< char > op;
int calculate(int operand1, int operand2, char op) //运算
{
int result;
switch (op)
{
case'+':result = operand1 + operand2; break;
case'-':result = operand2 - operand1; break;
case'*':result = operand1 * operand2; break;
case'/':result = operand2 / operand1; break;
case'^':result = pow(double(operand2), operand1); break;
}
return result;
}
void judgethepriority(char& c) //判断符号优先级并运算
{
if (op.empty())
{
op.push( c );
return;
}
char prev = op.top();
if (c == '+' || c == '-')
{
if (prev == '(')
{
op.push( c );
return;
}
int ope1 = operant.top();
operant.pop();
int ope2 = operant.top();
operant.pop();
int result = calculate(ope1, ope2, prev);
op.pop();
operant.push(result);
judgethepriority( c );
}
else if (c == '*' || c == '/')
{
if (prev == '(' || prev == '+' || prev == '-')
{
op.push(c);
return;
}
int ope1 = operant.top();
operant.pop();
int ope2 = operant.top();
operant.pop();
int result = calculate(ope1, ope2, prev);
op.pop();
operant.push(result);
judgethepriority( c );
}
else if (c == '^')
{
if (prev == '^')
{
int ope1 = operant.top();
operant.pop();
int ope2 = operant.top();
operant.pop();
int result = calculate(ope1, ope2, prev);
op.pop();
operant.push(result);
judgethepriority( c );
}
else
{
op.push( c );
return;
}
}
else if (c == ')')
{
if (prev == '(')
{
op.pop();
return;
}
int ope1 = operant.top();
operant.pop();
int ope2 = operant.top();
operant.pop();
int result = calculate(ope1, ope2, prev);
op.pop();
operant.push(result);
judgethepriority( c );
}
}
int main()
{
char c;
int number;
while (cin >> c && c != EOF)
{
switch ( c )
{
case' ':break;
case'+':judgethepriority( c ); break;
case'-':judgethepriority( c ); break;
case'*':judgethepriority( c ); break;
case'/':judgethepriority( c ); break;
case'^':judgethepriority( c ); break;
case'(':op.push( c ); break;
case')':judgethepriority( c ); break;
default:
cin.putback( c );
cin >> number;
operant.push(number);
break;
}
}
int goal;
while (!op.empty())
{
int n1 = operant.top();
operant.pop();
int n2 = operant.top();
operant.pop();
char op1 = op.top();
op.pop();
goal = calculate(n1, n2, op1);
operant.push(goal);
}
cout << operant.top() << endl;
return 0;
}