C++多位整数中序表达式计算

博客介绍了利用两个栈进行表达式计算的思路,一个栈存数,一个栈存操作符,计算表达式需以'='号结尾,且当前代码无法计算带小数点的算式,有待改进,并给出了相关代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

利用2个栈的思路,一个栈存储数,一个栈存储操作符。
计算表达式最后需要有’='号,例如

(37-5)/4*3=

此外,这个代码无法计算带小数点的算式,有待改进。

代码如下:

#include <iostream>
#include <string>
#include <stack>
#include <map>
using namespace std;

bool isDigital(char A) {
	if (A >= '0'&&A <= '9') {
		return true;
	}
	else
		return false;
}

double exec(double a, double b, char op) {
	switch (op)
	{
	case'+':
		return a + b;
	case'-':
		return a - b;
	case'*':
		return a * b;
	case'/':
		return a / b;
	}

}

double calcStr(string rstr)
{
	double result;
	map<char, int> isp;
	map<char, int> icp;
	isp['='] = icp['='] = 0;
	isp['('] = icp[')'] = 1;
	isp[')'] = icp['('] = 6;
	isp['+'] = isp['-'] = 3;
	isp['*'] = isp['/'] = 5;
	icp['+'] = icp['-'] = 2;
	icp['*'] = icp['/'] = 4;
	stack<char> op;
	stack<double> nums;
	op.push('=');
	int index = 0;
	while (rstr[index] !='=') {
		double tmp = 0;
		if (isDigital(rstr[index])) {		//多位数字处理
			while (isDigital(rstr[index])) {
				tmp = (tmp * 10) + (rstr[index] - '0');
				index++;
			}
			nums.push(tmp);
		}
		else if (icp[rstr[index]] > isp[op.top()]) {
			op.push(rstr[index]);
			index++;
		}
		else if (icp[rstr[index]] < isp[op.top()]) {
			double rnum = nums.top();
			nums.pop();
			double lnum = nums.top();
			nums.pop();
			double tmpRes = exec(lnum, rnum, op.top());//算出结果
			op.pop();
			nums.push(tmpRes);
		}
		else {
			if (op.top() == '(') {
				op.pop();
				index++;
			}
		}
	}
	while (op.top() != '=') {
		double rnum = nums.top();
		nums.pop();
		double lnum = nums.top();
		nums.pop();
		double tmpRes = exec(lnum, rnum, op.top());//算出结果
		op.pop();
		nums.push(tmpRes);
	}
	result = nums.top();
	return result;
}

int main()
{
	string inputString;
	cin >> inputString;
	cout << inputString << calcStr(inputString) << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值