运算符为+,-,*,/;操作数为整数;且没有括号
设定符号优先级,先在栈底压运算符0
#include<iostream> #include<cstdio> #include<cstring> #include<stack> using namespace std; stack<int> op; stack<double> num; char input[205]; bool prio[][5]= { 1,0,0,0,0, //0 1,0,0,0,0, //+ 1,0,0,0,0, //- 1,1,1,0,0, //* 1,1,1,0,0, //,/ }; void getNext(bool &isOp,int &opNum,int &loc) { if('0'<=input[loc]&&input[loc]<='9') { int tmp=0; while(input[loc]!=' '&&input[loc]!=0) { tmp*=10; tmp+=input[loc]-'0'; loc++; } isOp=0; opNum=tmp; if(input[loc]!=0) loc++; } else { isOp=1; if(input[loc]==0) opNum=0; else if(input[loc]=='+') opNum=1; else if(input[loc]=='-') opNum=2; else if(input[loc]=='*') opNum=3; else opNum=4; loc+=2; } } int main() { while(gets(input)) { while(!op.empty()) op.pop(); while(!num.empty()) num.pop(); if(strlen(input)==1&&input[0]=='0') break; bool isOp=0; int opNum=0,loc=0; op.push(0); while(loc<=strlen(input)) { getNext(isOp,opNum,loc); if(isOp==0) num.push(opNum); else { int opTop=op.top(); if(prio[opNum][opTop]==1) op.push(opNum); else { while(prio[opNum][opTop]==0) //这个地方之前出错,当当前运算符优先级比栈顶元素低,应该一直计算至栈顶元素优先级低于当前元素优先级 { double num2=num.top(); num.pop(); double num1=num.top(); num.pop(); int nowOp=op.top(); op.pop(); opTop=op.top(); if(nowOp==1) num.push(num1+num2); else if(nowOp==2) num.push(num1-num2); else if(nowOp==3) num.push(num1*num2); else if(nowOp==4) num.push(num1/num2); } op.push(opNum); } } } printf("%.2f ",num.top()); } return 0; }