推免复习-数据结构-栈应用-计算表达式(版本1)

这个表达式计算不出来emmm 2/(1+2+6/6/2-2)(8/2/2)
适用于 一位数的计算±/
/*()
代码还不够完善,希望可以写全面各种类型的计算器
每次写这个都卡壳,,,希望这次写好一些

#include<iostream>
#include<string>
#include<stack>
using namespace std;
class calculator
{
		private:
		string formula;
		stack<int>num;
		stack<char>op;
	public:
		calculator()
		{
			while(!num.empty())
			{
				num.pop();
			}
			while(!op.empty())
			{
				op.pop();
			}
		}
		~calculator()
		{
			while(!num.empty())
			{
				num.pop();
			}
			while(!op.empty())
			{
				op.pop();
			}
			formula="";
		}
	    bool input()
		{
			cin>>formula;
			if(formula=="END")
			{
				return false;
			}
			else return true;
		}
		void result();
		void cal();		
};
void calculator::cal()
{
	int n=formula.length();
	int i;
	for(i=0;i<n;i++)
	{
		if(formula[i]>='0'&&formula[i]<='9')
		{
			num.push(formula[i]-'0');
		}
		else if(formula[i]=='+'||formula[i]=='-')
		{
			while(!op.empty()&&op.top()!='(')
			{
				result();
			}
			op.push(formula[i]);
		}
		else if(formula[i]=='(')
		{
			op.push(formula[i]);
		}
		else if(formula[i]==')')
		{
			while(op.top()!='(')
			{
				result();
			}
			op.pop();
		}
		else if(formula[i]=='*'||formula[i]=='/')
		{
			if(op.empty()==true||op.top()=='+'||op.top()=='-'||op.top()=='(')
			{
				op.push(formula[i]);
			}
			else
			{
				while(op.top()=='*'||op.top()=='/')
				{
					result();
				}
			op.push(formula[i]);	
			}	
		}
		
	}
	while(!op.empty())
	{
		result();
	}
	cout<<num.top()<<endl; 
}
void calculator::result()
{
	int l,r,res;
	r=num.top();
	num.pop();
	l=num.top();
	num.pop();
	char c=op.top();
	op.pop();
	if(c=='+')
	res=r+l;
	else if(c=='-')
	res=l-r;
	else if(c=='*')
	res=l*r;
	else if(c=='/')
	res=l/r;
	num.push(res);
}
int main()
{
	calculator test;
	while(test.input())
	{
		test.cal();
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值