您的位置:首页 > 其它

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

2014-12-01 22:56 197 查看
//#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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: