中缀表达式变后缀表达式并求值

//#include "stdafx.h"
#include <iostream>
#include <stack>//包含栈类
#include <string>
using namespace std;
int prior(char op)//判断运算符号优先级
{
if (op == '+' || op == '-')//+ -优先级为1
return 1;
if (op == '*' || op == '/')//* /优先级为2
return 2;
return 0;
}
string TransForm(string infix)//转换中缀为后缀
{
stack<char> op;//中转栈 用于存放符号
string ans;//存放后缀表达式
for (unsigned int i = 0; i<infix.size(); i++)
{
char c = infix[i];
if (!((c >= 'A'&&c <= 'Z') || c == '(' || c == ')' || c == '*' || c == '/' || c == '+' || c == '-')) throw c;//异常处理
if (c >= 'A'&&c <= 'Z')//如果是字母直接入栈
{
ans.append(1, c); 
}
else
{
if (c == '(')//如果为左括弧入栈
op.push('(');
else
{
if (c == ')')//右括弧出栈 直到遇到左括弧为止
{
while (op.top() != '(')
{
ans.append(1, op.top());//栈顶元素写入ans
op.pop();
}
op.pop();
}
else//如果是+-*/符号
{
if (op.empty())//若栈空直接进栈
{
op.push(c);
}
else//不空
{
if (prior(c)>prior(op.top()))//优先级大直接进栈
op.push(c);
else
{
while (!op.empty() && prior(c) <= prior(op.top()))//直到找到优先级大于等于当前运算符的元素或者栈空
{
ans.append(1, op.top());//将栈顶元素写入ans
op.pop();//出栈
}
op.push(c);//将c入栈
}
}
}
}
}
}
while (!op.empty())
{
ans.append(1, op.top());
op.pop();
}
return ans;
}
double calculater(string postfix)//计算转化得到的表达式
{
stack<double> cal;
int j(0);
double left, right;
double a;
for (unsigned int i = 0; i < postfix.length(); i++)
{
if (postfix[i] <= 'Z'&&postfix[i] >= 'A')
{
cout << "请输入变量" << (char)(postfix[i]) << "的值" << endl;
cin >> a;
if (cin.fail())  throw j; 
if(postfix[i]=='('||postfix[i]==')') throw a;
cal.push(a);
j++;
}
else
{
right = cal.top();
cal.pop(); 
left = cal.top();
cal.pop(); 
if (postfix[i] == '+' ) cal.push(left + right);
if (postfix[i] == '-') cal.push(left - right);
if (postfix[i] == '*') cal.push(left * right);
if (postfix[i] == '/') cal.push(left / right);
}
}
return cal.top();


}
int main()
{
double result; 
string infix, postfix;
char c;
do{
try{
cout << "请输入中缀表达式,大写字母表示变量:" << endl;
cin >> infix;
postfix = TransForm(infix);
cout << "后缀表达式为:" << postfix << endl;
result = calculater(postfix);
cout << "表达式的值为:" << result << endl;
}
catch (char){ cout << "输入有误" << endl;  }
catch (int){ cout << "请输入数字谢谢!" << endl;  }
catch (double){cout<<"表达式有误"<<endl;}
cout<<"是否继续使用?y/n"<<endl;
cin>>c;
}while(c=='y');
return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值