表达式求值
2017-03-19 08:00
302 查看
表达式的三种记法:前缀表达式,中缀表达式,后缀表达式。
eg:
(1-2)*3+4/5:中缀表达式
12-3*45/+:后缀表达式
+*-123/45:前缀表达式
表达式求值(输入为int,除法为整除):
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; }
相关文章推荐
- 【NOIP2013普及组P2】表达式求值(NKOJ2500)题解
- 2016 UESTC Training for Data Structures N - 秋实大哥搞算数 CDOJ 1074 栈 表达式求值
- 表达式求值
- 栈的应用举例3(表达式求值)
- 【zzuli 1923 表达式求值】+ 字符串 + 栈
- 表达式求值
- 栈的应用——表达式求值
- 问题 C: 某计算器的超电磁炮(加减乘除括号表达式求值)
- 算数表达式求值
- 栈应用之逆波兰表达式与表达式求值
- 表达式求值顺序潜在的缺陷
- C/C++ 语言中的表达式求值
- nyoj 1272(表达式求值)
- nyoj305-表达式求值(栈。。dfs)
- nyoj35 表达式求值
- 【华为OJ】【096-表达式求值】
- 数据结构(C语言版)---第三章栈和队列 3.3 表达式求值
- 洛谷p1981 表达式求值
- 从中序表达式到逆序表达式(逆波兰式)(四则运算表达式求值)
- 基于python的单位正整数四则运算表达式求值