數據結構課本例題改進
#include#include #include #include 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 oper; stack num; l=strlen(str);oper.push('='); int sign=0,a=0; for(i=0;i ='0'&&str[i]<='9')||str[i]=='.'){ xz[a++]=str[i];sign=1; } else { if(sign==1){ xz[a]='';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 ,num.top()); } return 0; }
2 1.000+2/4=
((1+2)*5+1)/4=
1.50 4.00