中缀表达式转后缀并求值
来源:互联网 发布:商家给淘宝主播寄样品 编辑:程序博客网 时间:2024/05/17 23:33
这是个中缀表达式的求解,过程是先进行转换成后缀,然后我用的数组保存数,然后求解,我写的目前只限于单位数的中缀表达式…
#include<iostream>#include<stack>#include<string>using namespace std;int check(char buff) { if (buff == '+' || buff == '-')return 1; if (buff == '*' || buff == '/')return 2; if (buff == '(')return 3; if (buff == ')')return 4; return 0;}bool check_(char buff) { if (buff == '+' || buff == '-' || buff == '*' || buff == '/' || buff == '(' || buff == ')') return true; return false;}int main(void) { string buff; cin >> buff; stack<char>st; stack<char>num; for (int i = 0; i<buff.length(); i++) { if (check_(buff[i])) {//判定是否是运算符; if (st.empty()) st.push(buff[i]);//栈为空就先将运算符压入; else if (check(buff[i])>check(st.top())) {//当前运算符优先于栈顶运算符; if (check(buff[i]) == 4) { while (st.top() != '(') { num.push(st.top()); st.pop(); } if (st.top() == '(') { st.pop(); } } else { st.push(buff[i]); } } else {//当前运算符低于栈顶运算符; if (st.top() != '(') { num.push(st.top()); st.pop(); st.push(buff[i]); } else st.push(buff[i]); } } else num.push(buff[i]); } while (!st.empty()) {//将剩余运算符压入num栈; num.push(st.top()); st.pop(); } stack<char >te;//矫正顺序,num栈是逆序 while (!num.empty()) { cout << num.top(); te.push(num.top()); num.pop(); } cout<<endl; int i=0,arr[100]; while(!te.empty()){//用数组存取数字,然后求解; if(!check_(te.top())){ arr[i++]=te.top()-'0'; te.pop(); } else{ if (te.top() == '+'){ arr[i-2]+=arr[i-1]; i--; te.pop(); } else if (te.top() == '-'){ arr[i-2]-=arr[i-1]; i--; te.pop(); } else if (te.top()== '*'){ arr[i-2]*=arr[i-1]; i--; te.pop(); } else if (te.top() == '/'){ arr[i-2]/=arr[i-1]; i--; te.pop(); } } } cout<<arr[0]; return 0;}
阅读全文
0 0
- 中缀表达式转后缀表达式并求值
- 中缀表达式转后缀表达式并求值
- 中缀表达式转后缀表达式并求值
- 中缀表达式转后缀表达式并求值
- 中缀表达式转后缀并求值
- C语言 实现中缀表达式转后缀表达式并求值
- C++实现中缀表达式转后缀表达式并求值
- 中缀表达式变后缀表达式并求值
- 中缀表达式求值、后缀表达式求值、中缀转后缀、前缀
- 中缀转后缀 和 后缀表达式求值
- 中缀 后缀表达式求值
- NYOJ 35 表达式求值 【中缀转后缀+后缀表达式求值】
- 表达式求值(中缀转后缀及后缀表达式求值)
- C语言中缀表达式转后缀表达式并利用后缀表达式求值 (小于10)
- 中缀表达式转后缀表达式求值
- 中缀表达式转后缀表达式求值
- 中缀表达式转后缀表达式 求值
- 中缀转后缀及表达式求值
- 编写jQuery插件有哪些技巧?
- MySQL DATETIME类型和Timestamp之间的转换
- JSONP跨域请求原理及示例
- 面试题30:最小的k个数
- Eureka简介及原理
- 中缀表达式转后缀并求值
- 房卡麻将分析之”IPV6″改造
- [LeetCode] 110. Balanced Binary Tree
- 大型网站前端使用图片格式的正确姿势
- redis系列-事件
- 谷歌浏览器不能正常显示
- Xshell 颜色配置
- SCAN和KEYS 区别
- Java开发--oracle11g常用知识整理