#include <iostream> #include <stack> #include <cstio> #include <cstring> using namespace std; stack <float> data; stack <char> symbol; int b[5][6]; int change(char a){ int symbol_index; switch(a){ case '+':symbol_index=1;break; case '-':symbol_index=2;break; case '*':symbol_index=3;break; case '/':symbol_index=4;break; case '@':symbol_index=5;break; } return symbol_index; } int main () { memset(b,0,sizeof(b)); b[3][1]=b[3][2]=b[4][1]=b[4][2]=b[1][5]=b[2][5]=b[3][5]=b[4][5]=1; string a; cin >> a; symbol.push('@'); float index=0; for(int i=0;i<a.length();i++){ if(a[i]=='#'){ data.push(index); break; } if(a[i]<='9'&&a[i]>='0'){ index*=10; index+=a[i]-'0'; } else{ data.push(index); index=0; int symbol_index; symbol_index=change(a[i]); while(b[symbol_index][change(symbol.top())]==0){ float b=data.top(); data.pop(); float a=data.top(); data.pop(); switch(symbol.top()){ case '+':data.push(a+b);break; case '-':data.push(a-b);break; case '/':data.push(a/b);break; case '*':data.push(a*b);break; } symbol.pop(); } symbol.push(a[i]); } } while(symbol.top()!='@'){ float b=data.top(); data.pop(); float a=data.top(); data.pop(); switch(symbol.top()){ case '+':data.push(a+b);break; case '-':data.push(a-b);break; case '/':data.push(a/b);break; case '*':data.push(a*b);break; } symbol.pop(); } printf("%.4f",data.top()); return 0; }
Ideas: {
First read the recirculation {
If data, the index variable × 10+ data.
If the operator {
First index pushed onto the stack in data, then the index zero.
The operator is then converted into the code operators, see Table 1.
Then two cases: {
1. Symbol stack stack operator precedence this operator is not high: direct push.
2. Remove or symbol stack, the stack and data stack stack ( B) and the new top of the stack (the stack is taken out after the new top of the stack, i.e., from the second row down before removing the element) ( A) calculates then two cases to consider.
}
}
If it is #:index push to exit the loop.
}
And then finish the rest of the calculation. See 2.
}
Mistake: {
1. 除法应用float类型,我写成int了。
2. 栈改成int后,其他变量没改。
3. #时,index没入栈。(思路中已纠正)。
}
收获:{
1. 注意类型。
2. 结束时不要想当然地结束循环,而应思考一下还有什么操作。
}