算术表达式求值

第三题、条件表达式求值 
描述: 给定一个以字符串形式表示的算术表达式,计算该表达式的值。
表达式支持如下运算:“+、-、*、/”,其中“*”和“/”的优先级要高于“+”和“-”;
不需要考虑括号,且表达式之间没有空格;
例如:对于表达式"3-2+15*2",该表达式值为31.
 
运行时间限制: 60 Sec 
内存限制: 256 MByte 
输入: 加减乘除四则运算表达式,长度不超过1024字节,运算式中不含有括号和空格。

输出: 表达式的运算结果。

样例输入: 3-2+15*2

样例输出: 31

#include "iostream"
#include "string"
#include "stack"
using namespace std;

char Precede(char ch1,char ch2)
{
	if ((ch2 =='*'||ch2 =='/')&&(ch1 =='+'||ch1 =='-'))
	{
		return '>';
	}
	else
		return '<';
}

void calulate(char op,int num1,int num2,stack<int>& digit)
{
	int temp;

	switch(op)
	{
	case '+':
		temp =num2 +num1;
		break;
	case '-':
		temp =num2 -num1;
		break;
	case '*':
		temp =num2 *num1;
		break;
	case '/':
		temp =num2 /num1;
		break;
	}
	digit.push(temp);	
}
void cal(char* input)
{
	int len =strlen(input);
	stack<char> oper;
	stack<int> digit;
	int k=0;
	int sum =0;
	while(k<len)
	{
		if(input[k]>'0'&& input[k]<'9')
		{
			sum =0;
			while(input[k]>'0'&&input[k]<'9')
			{
				sum =sum*10 +input[k] -'0';
				k++;
			}
			digit.push(sum);
		}
		else
		{
			if (oper.empty())
			{
				oper.push(input[k]);
				k++;
			}
			else
			{
				if (Precede(oper.top(),input[k]) =='>')//如果输入的操作符的优先级大,则字符操作符入栈
				{
					oper.push(input[k]);
					k++;
				}
				else
				{
					int temp;
					int num1 =digit.top();
					digit.pop();
					int num2 =digit.top();
					digit.pop();
					char op =oper.top();
					oper.pop();
					calulate(op,num1,num2,digit);							
				}			
			}
		}
	}
	
	while(!oper.empty())
	{
		int temp;
		int num1 =digit.top();
		digit.pop();
		int num2 =digit.top();
		digit.pop();
		char op =oper.top();
		oper.pop();
		calulate(op,num1,num2,digit);	
	}

	cout<<digit.top()<<endl;
}

void main()
{
	char input[20];
	cin>>input;
	cal(input);
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值