用堆栈求表达式的值

#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;
}
输入一个以数字开头的表达式,表达式可以包含的运算符有+,-,*,/,^;以回车键结束输入
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值