The evaluation of arithmetic expressions is very common. Now, according to the requirements of the subject, a series of four arithmetic expressions are input, and the results of the expressions are obtained by the computer. The input arithmetic expression is required to input an integer arithmetic expression with correct syntax and no variables in the form of a sequence of characters. In computers, arithmetic expressions consist of constants, variables, operators and parentheses. Because different operators have different priorities, and parentheses should be considered, the evaluation of arithmetic expressions cannot be strictly carried out from left to right. Therefore, in programming, it is realized by stack. At this time, the experiment is to convert infix expression into suffix expression and then output it, and then continue to output suffix expression. This process is to initialize two stacks: operator stack s1 and stack s2 for storing intermediate results; Scan infix expressions from left to right; When an operand is encountered, it is pressed s2; When an operator is encountered, compare its priority with s1 stack top operator: if s1 is empty, or the stack top operator is left parenthesis "("), this operator will be directly put on the stack; Otherwise, if the priority is higher than that of the stack top operator, press the operator into s1; Otherwise, pop up the top operator of s1 and press it into s2, and go to (4.1) again to compare with the new top operator of s1; When parenthesis is encountered: if it is the left parenthesis "(",press S1 directly; If it is a right parenthesis ")", the operators on the top of s1 stack will pop up in turn, and s2 will be pressed in until the left parenthesis is encountered, at which time the pair of parentheses will be discarded; Repeat steps 2 to 5 until the rightmost part of the expression; Pop up the remaining operators in s1 in turn and press them into S2; The elements in s2 are popped up in turn and output. The result inverse is the suffix expression corresponding to the infix expression. Continue to scan suffix expression: if it is a number, let it stack; If it is an operator, two operands are taken out of the stack, the first one is taken as the right operand, and the second one is taken as the left operand, then the operator is operated and the result is put on the stack. Repeat the above process until the expression scan is completed. There is only one element left in the final stack, which is the result.
正在翻译中..