用堆栈求表达式的值

来源:互联网 发布:异星工厂 端口转发 编辑:程序博客网 时间: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;}
输入一个以数字开头的表达式,表达式可以包含的运算符有+,-,*,/,^;以回车键结束输入
原创粉丝点击