使用栈实现简单计算器

注意本代码只是简单实现了运算功能,而且字符串中的数字只能一位,除法运算结果最好不要有小数,因为没有准备小数相关功能,强行运算会中断程序或失去小数精确度。

#include<iostream>
#include<stack>
#include<map>
using namespace std;
//定义一个运算类
class run {
public:
	//临时保存数字
	stack<int>number;
	//临时保存运算符
	stack<char>op;
	//使用哈希表直接查询运算符号优先级
	map<char, int>map;
	//构造函数直接定义运算符优先级
	run() {
		map['+'] = map['-'] = 1;
		map['*'] = map['/'] = 2;
		map['('] = 0;
		map[')'] = 0;
	}
	//运算两个值
	int x(int a, int b, char op) {
		if (op == '+') {
			return a + b;
		}
		else if (op == '-') {
			return a - b;
		}
		else if (op == '*') {
			return a * b;
		}
		else {
			return a / b;
		}
	}
	//处理表达式
	int running(string expression) {
		//高级for循环,每次拿出一个字符
		for (auto it : expression) {
			//数字
			if (it >= '0' && it <= '9') {
				number.push(it-'0');
			}
			//运算符
			else {
				if (op.empty()) {
					op.push(it);
				}
				else {
					if (it == '(') {
						op.push(it);
					}
					else {
						while (!op.empty()&&op.top() != '(' && map[op.top()] > map[it]) {
							int a = number.top(); number.pop();
							int b = number.top(); number.pop();
							char c = op.top(); op.pop();
							number.push(x(b, a, c));
						}
						op.push(it);
					}
				}
			}
		}
		//当数字栈不为空
		while (number.size()>1) {
			int a = number.top(); number.pop();
			int b = number.top(); number.pop();
			char c;
			while ((c = op.top()) == '(' || c == ')') {
				op.pop();
			}
			number.push(x(b, a, c));
		}
		return number.top();
	}
};
int main() {
	cout << run().running("((4*3+5)*(2+4))*(5+5)") << endl;
}
  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Mystic Musings

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

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

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

打赏作者

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

抵扣说明:

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

余额充值