表达式计算的代码实现,按照前面两篇文章的逻辑步骤实现
来源:互联网 发布:淘宝客佣金代扣款给谁 编辑:程序博客网 时间:2024/06/06 17:12
#include <iostream> #include <string> #include <stack>using namespace std; //中缀表达式转后缀表达式string inFixToPostFix(string expr){ stack<char> opt; //操作符栈 string res = ""; int len = expr.size(); for (int i = 0; i < len; i++) { if (isdigit(expr[i])) //数字,直接保存到结果 { res += expr[i]; } else { if (i && isdigit(expr[i-1])) { res += ";"; //用;分割操作数和操作符 } if (opt.empty()) //如果栈是空,操作符直接入栈 { opt.push(expr[i]); } else { if (expr[i] == '(') //如果是左括号,直接入栈 { opt.push(expr[i]); } else if (expr[i] == '*' || expr[i] == '/') //*,/优先级比较高,所以只有*,、本身出栈 { while (!opt.empty() && (opt.top() == '*' || opt.top() == '/')) { res += opt.top(); res += ";"; opt.pop(); } opt.push(expr[i]); } else if (expr[i] == ')') //如果是右括号,左括号之后的出栈并保存到结果 { while (opt.top() != '(') { res += opt.top(); res += ";"; opt.pop(); } opt.pop(); //左括号出栈,不保存 } else { while (!opt.empty() && opt.top() != '(') //如果是+,-,除了左括号都要出栈并保存结果,因为+,-优先级低 { res += opt.top(); res += ";"; opt.pop(); } opt.push(expr[i]); //+,-运算符入栈 } } } } while(!opt.empty()) //栈不为空,剩下的操作符出栈 { res += ";"; res += opt.top(); opt.pop(); } return res;}//后缀表达式计算int evalPostFix(string expr){ int res = 0; stack<int> opr; //操作数栈 int len = expr.size(); int i, j; for (i = 0; i < len; i++) { if (expr[i] == ';') //;的作用是分割,直接过滤 { continue; } else if (isdigit(expr[i])) //遇到数字,往后查看,计算数值,入栈 { int num = 0; for (j = i; expr[j] != ';'; j++) { num = num * 10 + expr[j] - '0'; } opr.push(num); i = j; //这里之所以不是用i = ++j来跳过;,是因为第一层for循环中i++了 } else //遇到操作符,从栈中弹出两个数,计算结果,把结果入栈 { int right = opr.top(); opr.pop(); int left = opr.top(); opr.pop(); int t; switch(expr[i]) { case '+': t = left + right; opr.push(t); break; case '-': t = left - right; opr.push(t); break; case '*': t = left * right; opr.push(t); break; case '/': t = left / right; opr.push(t); break; } } } res = opr.top(); //最后,栈中保存的就是表达式计算结果 return res;}//测试算法void test(){ string infix = "90+(30-20)*3+10/2"; int res = 90 + (30 - 20) * 3 + 10 / 2; cout << inFixToPostFix(infix) << endl; int cal = evalPostFix(inFixToPostFix(infix)); cout << "res: " << res << " cal: " << cal << endl; if (res == cal) { cout << "right!\n"; } else { cout << "wrong!\n"; }}int main() { test(); return 0; }
0 0
- 表达式计算的代码实现,按照前面两篇文章的逻辑步骤实现
- 前面两篇文章的一点应用-DNS
- 关于Singleton的实现转两篇文章
- 正则表达式的两篇文章
- 后缀表达式计算的代码实现
- Flex开发中实现程序多语言的两篇文章
- 计算器C++代码实现—— 中缀表达式的计算
- 关于代码风格的两篇文章
- 用栈来实现表达式的计算
- 栈实现表达式的计算
- C++实现表达式的计算
- 字符串按照单词逆序的两种实现
- 接上篇文章的中缀与后缀的代码实现
- 实现TabHost的两种步骤
- 国家、城市等按照字母排序,但个别城市排在最前面的实现方法
- 数据统计计算的实现步骤
- 方便实现逻辑功能的代码
- 两篇文章的link
- dos 命令大全
- 采用新的方法解决extjs4.1 grid合并单元格问题
- FaceBook/infer-安装说明
- odoo(Openerp v8)数据模型
- HttpURLConnection(四)-多线程下载
- 表达式计算的代码实现,按照前面两篇文章的逻辑步骤实现
- [leetcode] Evaluate Reverse Polish Notation
- UNIX环境高级编程学习笔记(六)标准I/O库
- Android App的启动过程
- DataSnap服务器如何得到客户端的IP和端口
- 【MIG专项测试组】如何准确评测Android应用的流畅度?
- js里面的属性和方法类型
- SSL基础
- 黑马程序员--数组常用排序方法