您的位置:首页 > 其它

表达式计算(中缀转后缀,然后求值)

2017-04-18 17:16 211 查看
呕心沥血。。。写了一天,终于把这个恶心的东西写完了。。

下面的代码可以实现给出一个表达式,然后直接求值,应该算是表达式求值的裸题了,蓝桥杯有一道表达式计算就是这个题

题目链接:http://lx.lanqiao.cn/problem.page?gpid=T419

参考博客:http://blog.csdn.net/reidsc/article/details/54669433用后缀表达式求值的时候是照着写的。。

下面是我的代码:

#include <cstdio>
#include <cstring>
#include <cctype>
#include <string>
#include <set>
#include <iostream>
#include <stack>
#include <cctype>
#include <map>
#include <cmath>
#include <queue>
#include <vector>
#include <algorithm>
#define mem(a,b) memset(a,b,sizeof(a))
#define inf 0x3f3f3f3f
#define mod 10000007
#define debug() puts("what the fuck!!!")
#define N 100+20
#define M 1000000+10
#define ll long long
using namespace std;
char a[100];//存放转好的后缀表达式
stack<char>hpc;
stack<int>s3;//计算栈
int num[21];//暂时存放数字
map<char,int> mp;//定义运算符优先级
char s[100];//原来的中缀表达式
int len=0,sum;
int calc(int x,int y,char op)//两个数的运算
{
if(op=='+')return x+y;
if(op=='-')return x-y;
if(op=='/'&&y!=0)return x/y;
if(op=='*')return x*y;
}
void init()//把中缀表达式转换成后缀表达式
{
mp['+']=1;
mp['-']=1;
mp['*']=2;
mp['/']=2;
mp['(']=0;
scanf("%s",s);
int length=strlen(s);
for(int i=0; i<length; i++)
{
if(isdigit(s[i]))//当前这一位为数字
{
while(isdigit(s[i]))//
{
a[len++]=s[i];
i++;
}
i--;
a[len++]='#';//在数字后面加分隔符
}
else//是操作符
{
if(hpc.empty()||s[i]=='(')//栈为空且是左括号
{
hpc.push(s[i]);
}
else
{
if(s[i]==')')//遇到右括号时把前面的直到遇到左括号全部出栈并加入后缀表达式中
{
while(hpc.top()!='(')
{
a[len++]=hpc.top();
hpc.pop();
}
hpc.pop();//把左括号出栈
}
else
{
if(mp[s[i]]>mp[hpc.top()])//当当前符号的优先级高
4000
时,直接入栈
{
hpc.push(s[i]);
}
else
{
while(!hpc.empty()&&mp[hpc.top()]>=mp[s[i]])//当当前符号的优先级比较低时,出栈栈中优先级<=它的
{
a[len++]=hpc.top();
hpc.pop();
}
hpc.push(s[i]);//把当前的入栈
}
}
}
}
}
while(!hpc.empty())//把栈中剩下的元素加入后缀表达式中
{
a[len++]=hpc.top();
hpc.pop();
}
}
int solve()//后缀表达式计算
{
int x,y,tmp=0,k=0;
for(int i=0; i<len; i++)
{
if(a[i]=='#')
continue;
else if(a[i]=='+'||a[i]=='-'||a[i]=='*'||a[i]=='/')
{
x=s3.top();
s3.pop();
y=s3.top();
s3.pop();
x=calc(y,x,a[i]);
s3.push(x);
}
else//是数字
{
if(a[i+1]=='#')
{
num[k++]=a[i]-'0';
for(int i=0; i<k; i++)
tmp+=(num[i]*(int)pow(10,k-i-1));
s3.push(tmp);
tmp=0;
k=0;
}
else
{
num[k++]=a[i]-'0';
}
}
}
return s3.top();
}
int main()
{
init();//转换成后缀表达式
printf("%d\n",solve());

return 0;
}
//9+(3-1)*3+10/2
//1+((23+34)*5)-6
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: