2.表达式求值

给定一个字符串描述的算术表达式,计算出结果值。

输入字符串长度不超过100,合法的字符包括”+, -, *, /, (, )”,”0-9”,字符串内容的合法性及表达式语法的合法性由做题者检查。本题目只涉及整型计算。

参考代码:

#include <iostream>
#include <string>
#include <stack>
#include "stdlib.h"
using namespace std;
int pri(char m)
{
	switch(m)
	{	case '+':
		case '-':
			return 1;
		case '*':
		case '/':
			return 2;
		case '(':
		case ')':
			return 0;
		case '#':
			return -1;
		default:
			break;
	}
}
int getResult(string s)
{
	stack<int>value;
	stack<char>fuhao;
	s=s+"#$";
	if(s[0]=='-')
		s="0"+s;
	int i=0;
	string c="";
	while(s[i]!='$')
	{
		if(s[i]<='9'&&s[i]>='0')
		{
			c=c+s[i];
			i++;
			while(s[i]<='9'&&s[i]>='0')
			{
				c=c+s[i];
				i++;
			}
			i--;
			int m=atoi(c.c_str());
			value.push(m);
			c="";
		}

	else if(fuhao.size()==0||s[i]=='('||pri(s[i])>pri(fuhao.top()))
		fuhao.push(s[i]);
	else if(s[i]==')')
	{
		for(;fuhao.top()!='(';fuhao.pop())
		{
			char d=fuhao.top();
			int a=value.top();
			value.pop();
			int b=value.top();
			value.pop();
			switch(d)
			{
			case '+':
				{a=a+b;
				break;}
			case '-':
				{a=b-a;
				break;}
			case '*':
				{a=a*b;
				break;}
			case '/':
				{a=b/a;
				break;}
			default:
				break;
			}
			value.push(a);
		}
		fuhao.pop();
	}
	else
	{
		for(;fuhao.size()!=0&&pri(s[i])<=pri(fuhao.top());fuhao.pop())
		{char d=fuhao.top();
			int a=value.top();
			value.pop();
			int b=value.top();
			value.pop();
			switch(d)
			{
			case '+':
				{a=a+b;
				break;}
			case '-':
				{a=b-a;
				break;}
			case '*':
				{a=a*b;
				break;}
			case '/':
				{a=b/a;
				break;}
			}
			value.push(a);
		}
		fuhao.push(s[i]);
	}
	i++;
	}
	return value.top();
}

bool calculating(string str)
{

	cout<<getResult(str)<<endl;
	return true;
}

int main(void)
{
	string a;
	cin>>a;
	if(calculating(a))
	{
		cout<<"true"<<endl;
	}
	return 0;
}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值