Title description
Calculation of nonnegative integer constant arithmetic expressions, the available operators are: + - */(),
Enter
A set of nonnegative integer constant arithmetic expressions, each expression input line, the length of not more than 1024 characters,
O
Each expression output a line, the calculation results of the wrong expression of the output error,
The sample input Copy
12 + 5
- 4-7
3 - * 5
((12-3)/2) + 5
3 + 7/(2-2)
Sample output Copy
17
The error
The error
9
The error
my train of thought algorithm process:
E1: set up the operators and operands stack;
E2: # start operators into the stack, the expression string end operator added #;
E3: read the word expression and processing:
E31: if read as operands, then into the stack;
E32: if read for operator, then compared with the top operator:
E321: if the stack operator precedence than read operator:
Pop-up stack operator and two operands, and calculation and the results into the stack, step E32;
Operator precedence E322: if the stack is lower than read operator:
Will read the operator into the stack, step E3.
Operator precedence E323: if the stack is equal to read operator:
If #, calculate the end, if the brackets, the pop-up operator, step E3,
E4: check the stack state, to get results;
here is my code is mainly on the one hand, I can't think how to solve the problem of priority setting is comparing function value size tags like me? Or how should solve?
Ask elder help modify & amp; Train of thought,
# include
using namespace std;
{int flag (char c)
Int ret=0;
The switch (c) {
Case '+' : ret=1; break;
Case '-' : ret=1; break;
Case '*' : ret=2; break;
Case '/' : ret=2; break;
Case '(' : ret=3; break;
//case ') : ret=3; break;
Default: break;
}
return ret;
}
Int main () {
StackS1.
StackS2.
Char z='#';
S2. Push (z);
String x;
Cin> X;
X +="#";
E3: for (int I=0; iChar c=x [I];
If (isdigit (c)) {
If (flag (s2. Top ()) & gt; Flag (c)) {
Char y=s2. The top (); S2. Pop ();
Int the x1=s1. The top (); S1. Pop ();
Int x2=s1. The top (); S1. Pop ();
The switch (y) {
Case: '+' s1. Push (x1 + x2); break;
Case '-' : s1. Push (x1, x2); break;
Case '*' : s1. Push * (x1 x2); break;
Case '/' : s1. Push (x1 x2); break;
//case '(' : ret=3; break;
//case ') : ret=3; break;
Default: break;
}
Goto e3.
}
Else if (flag (s2. The top ()) & lt; Flag (c)) {
S2. Push (c);
continue;
}
Else if (flag (s2. The top ())==flag (c)) {
If (c=='#') break;
If (c=='(' | | c==') ') {
S2. Pop ();
continue;
}
}
}
The else {
S1. Push (c);
}
}
while(! S1. The empty ()) {
CoutS1. Pop ();
}
return 0;
}
CodePudding user response:
Turn the postfix expression calculation again