您的位置:首页 > 其它

表达式求值

2017-03-19 08:00 302 查看
表达式的三种记法:前缀表达式,中缀表达式,后缀表达式。

eg:

(1-2)*3+4/5:中缀表达式

12-3*45/+:后缀表达式

+*-123/45:前缀表达式

表达式求值(输入为int,除法为整除):

#include<cstdio>
#include<algorithm>
#include<iostream>
#include<string>
#include<cstring>
#include<stack>
#include<map>
using std::string;
using std::map;
using std::stack;
using std::cin;
using std::cout;
using std::endl;
string TOPostfix(string infix)//中缀式 转 后缀式
{
infix="("+infix+")";

map<char,int>priority;//优先级
string postfix; //后缀式
stack<char>mark;//符号栈

priority['+']=0;
priority['-']=0;
priority['*']=1;
priority['/']=1;

for(string::const_iterator str=infix.begin();str!=infix.end();++str)
{
switch(*str)
{
case '0':case '1':case '2':case '3':case '4':
case '5':case '6':case '7':case '8':case '9'://数字
postfix.push_back(*str);
break;

case '-':case '+':case '*':case '/'://运算符
if(*(str-1)!=')')
postfix.push_back('|');
while(!mark.empty()&&mark.top()!='('&&priority[mark.top()]>=priority[*str])//优先级大的先放
{
postfix.push_back(mark.top());
mark.pop();
}
mark.push(*str);
break;

case '('://左括号
mark.push(*str);
break;

case ')'://右括号
if(*(str-1)!=')')
postfix.push_back('|');
while(mark.top()!='(')//清空符号栈
{
postfix.push_back(mark.top());
mark.pop();
}
mark.pop();
}
}
// cout<<postfix<<endl;
return postfix;
}
int Clac(string postfix)
{
string strNum;//字符数字
stack<int>Res;//结果
int temp;//运算时用到的缓存变量
for(string::iterator str=postfix.begin();str!=postfix.end();++str)
{
switch(*str)
{
case '0':case '1':case '2':case '3':case '4':
case '5':case '6':case '7':case '8':case '9':
strNum.push_back(*str);//字符数字
break;

case '|'://str数字转int
temp=atoi(strNum.c_str());//atoi():str->int string.c_str()返回一个指向正规C字符串的指针
strNum.clear();
Res.push(temp);
break;

case '+'://+运算
temp=Res.top();
Res.pop();
Res.top()+=temp;
break;

case '-'://-运算
temp=Res.top();
Res.pop();
Res.top()-=temp;
break;

case '*'://*运算
temp=Res.top();
Res.pop();
Res.top()*=temp;
break;

case '/':// /运算
temp=Res.top();
Res.pop();
Res.top()/=temp;
}
}
return Res.top();
}
int main()//整数,整除
{
string infix,postfix;
cin>>infix;
postfix=TOPostfix(infix);
int res=Clac(postfix);
cout<<res<<endl;

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