利用两个栈求解算数表达式的源代码
2012-08-11 14:52
281 查看
说明:
1、只包含了小括号(),和+、-、*、/二元操作符的四则运算
2、求它更通用的求解方法可以参考递归求解、通过表达式树求解的方法
1、只包含了小括号(),和+、-、*、/二元操作符的四则运算
2、求它更通用的求解方法可以参考递归求解、通过表达式树求解的方法
#include <cctype> #include <map> #include <stack> #include <string> #include <iostream> using namespace std; //弹出操作符栈的一个操作符,弹出操作数栈的一个操作数,计算结果 void Compute(stack<char> &operators, stack<double> &operands) { double op2 = operands.top(); operands.pop(); double op1 = operands.top(); operands.pop(); char optr = operators.top(); double result; switch(optr) { case '+': result = op1 + op2; case '-': result = op1 - op2; case '*': result = op1 * op2; case '/': result = op1 / op2; } operands.push(result); operators.pop(); } //通过操作符栈和操作数栈求解表达式,表达式正确返回true,结果存在result里,错误返回false bool ComputeExpr(const string &expr, map<char,int> &priority_tbl, double &result) { stack<double> operands;//操作数栈 stack<char> operators;//操作符栈 string inner_expr(expr + '$');//加个哨兵 operators.push('#');//哨兵 for(int i = 0; i < inner_expr.length(); ++i) { char ch = inner_expr[i]; if(isdigit(ch))//操作数直接入操作数栈 operands.push(ch - 0x30); else//操作符 { switch(ch) { case '(': operators.push(ch); break; case ')': //求解当前最内部的括号表达式 while(operators.top() != '(') { if(operators.top() == '#' || operands.size() < 2) return false; Compute(operators, operands); } operators.pop(); break; case '$': //此时,正确表达式已经不存在括号了,计算 while(operators.top() != '#') { if(operands.size() < 2) return false; Compute(operators, operands); } if(operands.size() == 1) { result = operands.top(); return true; } return false; default: //一般的二元操作符求解 while(priority_tbl[ch] <= priority_tbl[operators.top()]) { if(operands.size() < 2) return false; Compute(operators, operands); } operators.push(ch); } } } } int main(int argc, char *argv[]) { const string expr_str("((5+6)*7/(2-9)*9)+5"); //优先级表,数字越大,优先级越高 map<char, int> priority_tbl; priority_tbl.insert(make_pair('+',2)); priority_tbl.insert(make_pair('-',2)); priority_tbl.insert(make_pair('*',3)); priority_tbl.insert(make_pair('/',3)); priority_tbl.insert(make_pair('(',1)); priority_tbl.insert(make_pair('#',0)); double result; bool ret = ComputeExpr(expr_str, priority_tbl, result); if(ret) { cout << expr_str << " = " << result << endl; } else { cout << "表达式错误!" << endl; } return 0; }
相关文章推荐
- 利用栈对四则运算简单表达式求解的测试(中缀表达式)
- 利用逆波兰表达式求算数表达式的值
- 利用堆栈求解算术表达式 利用递归求解算术表达式
- 利用栈进行表达式求解
- 第十一周项目2-用二叉树求解算数表达式
- 【数据结构】利用栈 求解表达式
- 利用堆栈求解算术表达式
- C++:基于高精度运算的算数表达式求解
- 利用notepad++和正则表达式快速清除源代码行号
- 利用堆栈计算算数表达式
- 前缀式(波兰式)与后缀式(逆波兰式)求解表达式的值,中缀式(一般算数表达式不做讨论)
- 利用逆波兰表达式(后缀表达式)解析四则运算表达式的详细源代码及解释
- 利用正则表达式求解多项式相乘问题
- 零碎的数据结构与算法——Dijkstra双栈算数表达式求解
- 利用栈进行表达式求解
- 计算机求解可溢出的两个整型数相乘,算数运算溢出解决方法
- 《数据结构与算法》学习笔记12 利用栈解析算数表达式
- 利用栈计算算数表达式的值
- 利用栈计算算数表达式的值
- 第十二周项目四----利用遍历思想求解图问题之输出一些简单回路