小型计算器(后缀表达式计算)

对于普通的四则混合运算,可以将表达式通过转换成逆波兰式来进行计算。具体是通过栈来进行实现的,代码如下:

代码:

#include<iostream>
#include<cstdio>
#include<stack>
#include<sstream>
#include<string>

using namespace std;
string in, post;
stack<char>st;
stack<int>p;

void i2s(string str, int& num)
{
	stringstream ss;
	ss << str;
	ss >> num;
}

void turn()         //中缀表达式转换成后缀表达式
{
	int i;
	char ch;
	for (i = 0; i < (int)in.size(); ++i) {
		switch (in[i])
		{
		case '+':
		case '-':
			if (!st.empty() && st.top() != '(') {
				post.push_back(st.top());
				st.pop();
			}
			st.push(in[i]);
			break;
		case '*':
		case '/':
			if (!st.empty() && (st.top() == '*' || st.top() == '/')) {
				post.push_back(st.top());
				st.pop();
			}
			st.push(in[i]);
			break;
		case '(':
			st.push(in[i]);
			break;
		case ')':
			ch = st.top(); st.pop();
			post.push_back(ch);
			st.pop();
			break;
		default:
			while ('0' <= in[i] && in[i] <= '9') {
				post.push_back(in[i]);
				++i;
			}
			post.push_back('#'); i--;
			break;
		}
	}
	while (!st.empty()) {
		post.push_back(st.top());
		st.pop();
	}
}

int cal()         //通过后缀表达式计算,获得结果
{
	int i, x, a, b;
	string num;
	for (i = 0; i < (int)post.size(); ++i) {
		if ('0' <= post[i] && post[i] <= '9') {
			while ('0' <= post[i] && post[i] <= '9')
				num.push_back(post[i++]);
			i2s(num, x); p.push(x); num.clear();
		}
		else {
			b = p.top(); p.pop();
			a = p.top(); p.pop();
			switch (post[i])
			{
			case '+':
				x = a + b;
				break;
			case '-':
				x = a - b;
				break;
			case '*':
				x = a * b;
				break;
			case '/':
				x = a / b;
				break;
			default:
				break;
			}
			p.push(x);
		}
	}
	return p.top();
}

int main()
{
	int i, j;
	cin >> in;
	turn();
	cout << cal() << endl;
	return 0;
}
/*
1+2*3
((1+2)*3+5)*6
*/
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值