用堆栈求表达式的值
来源:互联网 发布:异星工厂 端口转发 编辑:程序博客网 时间:2024/06/03 13:07
#include<cmath>#include<iostream>#include<stack>#include<algorithm>#include<stdexcept>#include<string>using namespace std;double execute(stack<char>&ops, stack<double>&operands){double result{};double rhs{ operands.top() };operands.pop();double lhs{ operands.top() };operands.pop();switch (ops.top()){case '+':result = rhs + lhs;break;case '-':result = lhs - rhs;break;case '*':result = rhs * lhs;break;case '/':result = lhs / rhs;break;case '^':result = pow(lhs, rhs);break;default:throw runtime_error{ string{"invilid operator: "}+ops.top() };}ops.pop();operands.push(result);}size_t precedence(const char op){if (op == '+' || op == '-'){return 1;}else if (op == '*' || op == '/'){return 2;}else if (op == '^'){return 3;}elsethrow runtime_error{ string{"invalid operator: "}+op };}int main(){stack<double> operands;stack<char>operators;string exp;cout << "A arithmatic expression can include the oprators + - * / "<< " and ^ for exponentiation. " << endl;try{while (true){cout << "Enter an arithmatic expression and press Enter "<< " - enter an empty line to end: " << endl;getline(cin, exp, '\n');if (exp.empty())break;//remove spacesexp.erase(remove(begin(exp), end(exp), ' '), end(exp));size_t index{};//Every expression must start with a numerical operandoperands.push(stod(exp, &index));while (true){//push the oprator on to the stackoperators.push(exp[index++]);//Get rhs operandsize_t i{};//Index to substring//Push rhs operandoperands.push(stod(exp.substr(index), &i));//Increment expression indexindex += i;//If we are at end of exp...if (index == exp.length()){//...execute outstanding opswhile (!operators.empty())execute(operators, operands);break;}//If we reach here ,there's anothor op...//If there's a previous op of equal or higher precedence excute itwhile (!operators.empty() && precedence(exp[index]) <= precedence(operators.top())){//excute previous op.execute(operators, operands);}}cout << "result = " << operands.top() << endl;}}catch (const std::exception& e){cerr << e.what() << endl;}std::cout << "Calculator ending...." << endl;return 0;}输入一个以数字开头的表达式,表达式可以包含的运算符有+,-,*,/,^;以回车键结束输入
阅读全文
0 0
- 用堆栈求表达式的值
- 用堆栈把中缀表达式转化为后缀表达式,之后再求后缀表达式结果
- 《数据结构学习与实验指导》3-7求前缀表达式的值/3-8堆栈模拟队列
- 栈求表达式的值
- 求中缀表达式的值
- 求字符串表达式的值.
- 求前缀表达式的值
- 求后缀表达式的值
- 求算术表达式的值
- 求后缀表达式的值
- 求前缀表达式的值
- 求前缀表达式的值
- 简单的用堆栈实现的表达式计算
- 中缀表达式转后缀表达式_求表达式的值
- 关于用堆栈实现中后缀表达式计算的问题
- 堆栈实现中缀表达式转后缀表达式及计算表达式的值
- 带求最小值的堆栈算法
- 解释一个求表达式值的过程?
- 677
- XML语法
- 对抗攻击最新研究:仅修改「一个像素」即可骗过神经网络!
- 算法储备之有向无环图的最短路径问题
- Android开发:ListView、AdapterView、RecyclerView全面解析
- 用堆栈求表达式的值
- [小程序开发] silk 转 MP3 ,第三步
- 设计模式详解
- 纯CSS的CheckBox
- MySQL数据类型
- 背包、队列和栈
- Angular表格的导入导出
- CentOS 7查看系统版本及查看机器位数x86-64 & centOS7下实践查询版本/CPU/内存/硬盘容量等硬件信息
- JDBC纯驱动方式连接Oracle