表达式计算 四则运算(有括号)的计算

问题描述
  输入一个只包含加减乖除和括号的合法表达式,求表达式的值。其中除表示整除。
输入格式
  输入一行,包含一个表达式。
输出格式
  输出这个表达式的值。
样例输入
1-2+3*(4-5)
样例输出
-4
数据规模和约定
  表达式长度不超过100,表达式运算合法且运算过程都在int内进行。





#include<bits/stdc++.h>
using namespace std;
char str[110];
stack<int> sInt;     //数字 
stack<char> sChar;   //运算符 
bool iso(char c)   //判读是否为运算符 
{
	if(c=='+' || c=='-' || c=='*' || c=='/' || c=='(' || c==')')
		return true;
	return false;
}
int getRank(char c)   //获取优先级 
{
	if(c=='*' || c=='/')
		return 2;
	else if(c=='+' || c=='-')
		return 1;
	return 0;
}
void calc()       //计算 
{
	int b = sInt.top(); sInt.pop();
	int a = sInt.top(); sInt.pop();
	int c = sChar.top();sChar.pop();
	int d;
	if(c=='+')
		d = a+b;
	else if(c=='-')
		d = a-b;
	else if(c=='*')
		d = a*b;
	else
		d = a/b;
	sInt.push(d);
}
int main()
{
	scanf("%s",str);
	int len = strlen(str);
	for(int i=0;i<len;i++)
	{
		if(iso(str[i]))   //如果不为数字 
		{
			if(str[i]=='(')
				sChar.push(str[i]);
			else if(str[i]==')')      //将括号中的全部算完 
			{
				int c = sChar.top();
				while(c!='(')
				{
					calc();
					c = sChar.top();
				}
				sChar.pop();
			}
			else
			{
				int r = getRank(str[i]);   //获取优先级 
				if(sChar.empty() || r>getRank(sChar.top()))   
					sChar.push(str[i]);
				else                //如果后面的优先级小于等于前面的就把前面的运算算出 
				{
					calc();
					sChar.push(str[i]);
				}
			}
		}
		else    //为数字 
		{
			int t;
			sscanf(str+i,"%d",&t);     
			sInt.push(t);            //将数字入栈 
			for(;!iso(str[i+1]);i++);    //跳到是运算符的地方 
		}
		
	}
	while(!sChar.empty())
	{
		calc();
	}
	printf("%d\n",sInt.top());
}






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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值