蓝桥杯算法训练 表达式计算

来源:互联网 发布:java 字符串 == 编辑:程序博客网 时间:2024/06/15 08:14
#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;elsereturn -1;case '-':if(y=='+'||y=='-'||y==')'||y=='#')return 1;elsereturn -1;case '*':if(y=='(')return -1;elsereturn 1;case '/':if(y=='(')return -1;elsereturn 1;case '(':if(y==')')return 0;elsereturn -1;case ')':return 1; //如果表达式是合法的,')'不可能入栈,这种情况不会发生case '#':if(y=='#')return 0;elsereturn -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();elsestk2.push(str[i]);}i++;}int res=stk1.top();cout<<res<<endl;return 0;} 

0 1
原创粉丝点击