#include <cmath>
#include <cstdio>
#include <algorithm>
#include <stack>
#include <iostream>
#include <cstring>
using namespace std;
char str[105];
int i=0;
/*
int priority(char x,char y) //这个函数是错误的,原因在于编译器不能识别 这个表达式(y='(')
{ //它把最后一个 ) 与第二个 ( 匹配了,而我们认为第二个 ( 是一个字符
//也就是括号匹配总是寻找邻近的
if(x=='+'||x=='-'&&(y=='*'||y=='(' )||y=='/' ))
return -1;
else if(x=='+'||x=='-'&&(y=='+'||y=='-'||y==')'||y=='#'))
return 1;
if(x=='*'||x=='/'&&(y=='('))
return -1;
if(x=='*'||x=='/'&&(y=='+'||y=='-'||y=='*'||y=='/'||y==')'||y=='#'))
return 1;
if(x=='('&&(y=='+'||y=='-'||y=='*'||y=='/'||y=='('))
return -1;
if(x=='('&&y==')')
return 0;
if(x==')')
return 1;
if(x=='#'&&(y=='+'||y=='-'||y=='*'||y=='/'||y=='('))
return -1;
if(x=='#'&&y=='#')
return 0;
}
*/
int priority(char x,char y)
{ //栈顶x,与当前扫描到y比较优先权
//栈顶小,返回-1 相等,返回0 大于返回1
switch(x)
{
case '+':
if(y=='+'||y=='-'||y==')'||y=='#')
return 1;
else
return -1;
case '-':
if(y=='+'||y=='-'||y==')'||y=='#')
return 1;
else
return -1;
case '*':
if(y=='(')
return -1;
else
return 1;
case '/':
if(y=='(')
return -1;
else
return 1;
case '(':
if(y==')')
return 0;
else
return -1;
case ')':
return 1; //如果表达式是合法的,')'不可能入栈,这种情况不会发生
case '#':
if(y=='#')
return 0;
else
return -1;
}
}
int compute(int left,char op,int right)
{
if(op=='+') return left+right;
if(op=='-') return left-right;
if(op=='*') return left*right;
if(op=='/') return left/right;
}
int main()
{
stack<int> stk1;
stack<char> stk2;
scanf("%s",str);
char strr[2]="#";
strcat(str,strr);
stk2.push('#');
while(str[i]!='\0')
{
int x=0;
while(str[i]>='0'&&str[i]<='9')
{
x=x*10+str[i]-'0';
i++;
}
if(x!=0) //输入不能输入0+5这种不合法的数据
stk1.push(x);
if(priority(stk2.top(),str[i])==-1)
stk2.push(str[i]);
else if(priority(stk2.top(),str[i])==0)
stk2.pop();
else
{
while(priority(stk2.top(),str[i])==1)
{
char op=stk2.top();stk2.pop();
int y=stk1.top();stk1.pop();
int x=stk1.top();stk1.pop();
stk1.push(compute(x,op,y));
}
if(priority(stk2.top(),str[i])==0)
stk2.pop();
else
stk2.push(str[i]);
}
i++;
}
int res=stk1.top();
cout<<res<<endl;
return 0;
}
蓝桥杯算法训练 表达式计算
最新推荐文章于 2022-04-08 11:27:00 发布