数算 中缀表达式求值 栈

中缀表达式求值
通过把“中缀转后缀”和“后缀求值”两个算法功能集成在一起(非简单的顺序调用),实现对中缀表达式直接求值,新算法还是从左到右扫描中缀表达式,但同时使用两个栈,一个暂存操作符,一个暂存操作数,来进行求值。(支持 + - * / ^ 五种运算)
输入样例:
( 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值