用栈的知识实现四则运算(带括号的加减乘除)

#include<iostream>
#include<string>
#include<vector>
#include<stack>
using namespace std;
void size_yunsuan(string input,string &a)
{
	int i=0;
	int length=input.size();
	stack<char> stack1;
	while(i<length)
	{
		//cout<<input[i]<<endl;
		if(input[i]>='0'&&input[i]<='9')
			a.push_back(input[i]);
		if(input[i]=='+'||input[i]=='-')
		{
			if(stack1.empty()||stack1.top()=='('||stack1.top()=='+'||stack1.top()=='-')
			{

				stack1.push(input[i]);
			}
			else 
			{
				while(!stack1.empty())
				{
					a.push_back(stack1.top());
					stack1.pop();
				}
			}
		}
		if(input[i]=='(')
			stack1.push(input[i]);
		if(input[i]==')')
		{
			while(stack1.top()!='(')
			{
				a.push_back(stack1.top());
				stack1.pop();
			}
			stack1.pop();
		}
		if(input[i]=='*'||input[i]=='/')
		{
			stack1.push(input[i]);
		}
		i++;
	}
	while(!stack1.empty())
	{
		a.push_back(stack1.top());
				stack1.pop();
	}

}

int yunsuan(string a)
{
	if(a.size()==0)
		return -1;
	int i=0;
	int length=a.size();
	stack<int> temp;
	int key=0;
	int first,second;
	while(i<length)
	{
		cout<<a[i]<<endl;
		if(a[i]>='0'&&a[i]<='9')
			temp.push(a[i]-'0');
		else
		{
		   switch (a[i])
		   {
		   case '+':
			   first=temp.top();
			   temp.pop();
			   second=temp.top();
			   temp.pop();
			   key=first+second;
			   temp.push(key);
			   break;
		   case '-':
			   first=temp.top();
			   temp.pop();
			   second=temp.top();
			   temp.pop();
			   key=second-first;
			   temp.push(key);
			   break;
		   case '*':
			   first=temp.top();
			   temp.pop();
			   second=temp.top();
			   temp.pop();
			   key=second*first;
			   temp.push(key);
			   break;
		   case '/':
			   first=temp.top();
			   temp.pop();
			   second=temp.top();
			   temp.pop();
			   key=second/first;
			   temp.push(key);
			   break;
		 //  default:
			   //break;

		   }
		}
		++i;
	}
	return temp.top();
}
void calculate(string s)
{
	string a;
	size_yunsuan(s,a);
	cout<<yunsuan(a)<<endl;;
}
int main()
{
	string s("(3+5)/8");
	calculate(s);
	system("pause");
	return 0;
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值