标签:nyoj表达式求值
2 1.000+2/4=
((1+2)*5+1)/4=
1.50 4.00
#include<cstdio> #include<cstdlib> #include<cstring> #include<stack> using namespace std; char str[1010],xz[1010]; char compare(char proper,char baoper){ if(proper=='+'){ if(baoper=='*'||baoper=='/'||baoper=='(')return '<'; else return '>'; } else if(proper=='-'){ if(baoper=='*'||baoper=='/'||baoper=='(')return '<'; else return '>'; } else if(proper=='*'){ if(baoper=='(')return '<'; else return '>'; } else if(proper=='/'){ if(baoper=='(')return '<'; else return '>'; } else if(proper=='('){ if(baoper==')')return '='; else return '<'; } else if(proper==')')return '>'; else if(proper=='='){ if(baoper=='=')return '='; else return '<'; } } double count(double a,char b,double c){ if(b=='+') return a+c; else if(b=='-')return a-c; else if(b=='*')return a*c; else if(b=='/')return a/c; } int main() { int k,i,l; double b,d,p; scanf("%d",&k); while(k--){ scanf("%s",str); stack<char>oper; stack<double>num; l=strlen(str);oper.push('='); int sign=0,a=0; for(i=0;i<l;++i){ if((str[i]>='0'&&str[i]<='9')||str[i]=='.'){ xz[a++]=str[i];sign=1; } else { if(sign==1){ xz[a]='\0';sscanf(xz,"%lf",&p); num.push(p);a=0;sign=0; } switch (compare(oper.top(),str[i])){ case '<': oper.push(str[i]); break; case '>': b=num.top();num.pop(); d=num.top();num.pop(); num.push(count(d,oper.top(),b)); oper.pop(); i--; break; case '=': oper.pop(); break; } } } printf("%.2lf\n",num.top()); } return 0; }
标签:nyoj表达式求值
原文地址:http://blog.csdn.net/r1986799047/article/details/43492519