用堆栈求表达式的值

#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;
}
输入一个以数字开头的表达式,表达式可以包含的运算符有+,-,*,/,^;以回车键结束输入
DS堆栈是一种常见的数据结构,用于实现表达式计算。在使用C语言中的stack堆栈对象来实现时,可以参考课本中的伪代码,并将其改造成可运行的代码。首先,需要包含头文件#include <stack>,然后创建一个stack对象来表示堆栈。接下来,可以按照以下步骤进行表达式计算: 1. 遍历表达式中的每个字符。 2. 如果遇到数字,将其转换为对应的数,然后将其压入堆栈。 3. 如果遇到操作符(如+、-、*、/等),从堆栈中弹出两个数字进行运算,并将结果压入堆栈。 4. 当遍历完整个表达式后,堆栈中只剩下一个数字,即为表达式的计算结果。 以下是一个示例代码,其中假设表达式存储在一个字符串中: #include <iostream> #include <stack> #include <cctype> #include <cstring> using namespace std; int calculateExpression(const char* expression) { stack<int> numStack; int len = strlen(expression); for (int i = 0; i < len; i++) { if (isdigit(expression[i])) { int num = 0; while (i < len && isdigit(expression[i])) { num = num * 10 + (expression[i] - '0'); i++; } numStack.push(num); } else if (expression[i] == '+' || expression[i] == '-' || expression[i] == '*' || expression[i] == '/') { int num2 = numStack.top(); numStack.pop(); int num1 = numStack.top(); numStack.pop(); int result; switch (expression[i]) { case '+': result = num1 + num2; break; case '-': result = num1 - num2; break; case '*': result = num1 * num2; break; case '/': result = num1 / num2; break; } numStack.push(result); } } return numStack.top(); } int main() { const char* expression = "2 1 2*3-4/5#"; int result = calculateExpression(expression); cout << "计算结果:" << result << endl; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值