标签:
1 + 2 4 + 2 * 5 - 7 / 11 0
3.00 13.36
Code:
#include <cstdio> #include <cstring> #include <stack> using namespace std; int compare[][5]={ {1,0,0,0,0}, {1,0,0,0,0}, {1,0,0,0,0}, {1,1,1,0,0}, {1,1,1,0,0} }; stack<int> Operation; stack<double> Number; void getNext(char str[],bool &retOp,int &retNum,int &index){ //函数结束时,如果retOp为true,说明该字符为 if(index==0&&Operation.empty()==true){ //运算符,retNum为运算符编号;如果retOp为false, retOp=true; //说明该字符是数字,retNum为该数字大小 retNum=0; return; } if(str[index]==0){ retOp=true; retNum=0; return; } if(str[index]>=‘0‘&&str[index]<=‘9‘){ retOp=false; }else{ retOp=true; if(str[index]==‘+‘) retNum=1; if(str[index]==‘-‘) retNum=2; if(str[index]==‘*‘) retNum=3; if(str[index]==‘/‘) retNum=4; index=index+2; return; } retNum=0; for( ;str[index]!=‘ ‘&&str[index]!=0;++index){ retNum=retNum*10; retNum=retNum+str[index]-‘0‘; } if(str[index]==‘ ‘) ++index; return; } int main() { const int arrSize=210; char str[arrSize]; while(gets(str)){ if(str[0]==‘0‘&&str[1]==0) break; bool retOp; int retNum; int index=0; while(Operation.empty()==false) Operation.pop(); while(Number.empty()==false) Number.pop(); while(true){ getNext(str,retOp,retNum,index); if(retOp==false){ Number.push((double)retNum); }else{ if(Operation.empty()==true||compare[retNum][Operation.top()]==1){ Operation.push(retNum); }else{ double temp=0.0; while(compare[retNum][Operation.top()]==0){ int op=Operation.top(); Operation.pop(); double b=Number.top(); Number.pop(); double a=Number.top(); Number.pop(); if(op==1) temp=(double)a+b; if(op==2) temp=(double)a-b; if(op==3) temp=(double)a*b; if(op==4) temp=(double)a/b; Number.push((double)temp); } Operation.push(retNum); } } if(Operation.size()==2&&Operation.top()==0) break; } printf("%.2f\n",Number.top()); } return 0; } /************************************************************** Problem: 1019 User: lcyvino Language: C++ Result: Accepted Time:0 ms Memory:1524 kb ****************************************************************/
标签:
原文地址:http://www.cnblogs.com/Murcielago/p/4197118.html