⌈C++11⌋实现一个简易计算器

文章介绍了如何使用C++实现一个简单的算术表达式解析器,通过数据栈和运算符栈处理加减乘除等运算,遵循正确的运算顺序。

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

 原理:

数据栈:有数据就直接入栈

运算符栈:设遍历到当前的运算符位e,如果栈不为空,比较栈顶与当前运算符优先级e,当栈顶运算符优先级大于或者等于e的优先级,则出栈,并将两个数据栈的数据出栈,计算出对应的数据,加入到数据栈中,否则将运算符入栈

#include <iostream>
#include <unordered_map>
#include <stack>
#include <functional>
#include <string>


#define MAX_PRI INT_MAX

using namespace std;
int main() {
	//数据栈
	stack<double> _data;   
	//运算符栈
	stack<char> _operator;   
	//运算符优先级
	unordered_map<char, int> pri{ {'+', 0}, {'-', 0}, {'*', 1}, 
                                  {'/', 1}, {'^', 2}, {'(', MAX_PRI }, 
                                  {')', MAX_PRI}};
	unordered_map<char, function<double(double, double)>> func{
		{'+', [](double x, double y) -> double { return x + y; }},
		{'-', [](double x, double y) -> double { return x - y; }},  
		{'*', [](double x, double y) -> double { return x * y; }},
		{'/', [](double x, double y) -> double { return x / y; }},
		{'^', [](double x, double y) -> double { return pow(x, y); }}

	};

	string exp;
	cin >> exp;

	auto calculate = [&_data, &_operator, &func]() {
		char op = _operator.top();
		_operator.pop();
		double x = _data.top();
		_data.pop();
		double y = _data.top();
		_data.pop();
		_data.push(func[op](y, x));   //运算顺序与出栈顺序相反
	};
	auto stringtonum = [&exp, &pri](int& i) -> double {
		int j = i + 1;
		while (j < exp.length() && pri.find(exp[j]) == pri.end()) j++;
		double num = stod(exp.substr(i, j - i));
		i = j - 1;   
		return num;
	};

	for (int i = 0; i < exp.length(); ++i) {
		char e = exp[i];
		if (pri.find(e) == pri.end()) {   //当前字符不是运算符,则切割数字
			_data.push(stringtonum(i));
		} else if (e == '(') {
			_operator.push('(');
		} else if (e == ')') {
			while (_operator.top() != '(') {
				calculate();
			}
			_operator.pop();
		} else {
			//当前运算符优先级<=栈顶运算符优先级,则出栈计算
			while (!_operator.empty() && pri[_operator.top()] >= pri[e] && _operator.top() != '(') {
				calculate();
			}
			_operator.push(e);
		}
	}
	while (!_operator.empty()) {
		calculate();
	}
	cout << _data.top() << endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dusong_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值