#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;
}
else
throw 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 spaces
exp.erase(remove(begin(exp), end(exp), ' '), end(exp));
size_t index{};
//Every expression must start with a numerical operand
operands.push(stod(exp, &index));
while (true)
{
//push the oprator on to the stack
operators.push(exp[index++]);
//Get rhs operand
size_t i{};//Index to substring
//Push rhs operand
operands.push(stod(exp.substr(index), &i));
//Increment expression index
index += i;
//If we are at end of exp...
if (index == exp.length())
{
//...execute outstanding ops
while (!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 it
while (!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;
}
输入一个以数字开头的表达式,表达式可以包含的运算符有+,-,*,/,^;以回车键结束输入
用堆栈求表达式的值
最新推荐文章于 2020-01-06 11:19:14 发布