更新时间:2021-07-08 10:28:15
Reverse Polish Notation 是一种编写表达式的特定方式,首先编写值,然后编写要执行的操作.例如,要将数字 3 和 4 相加,您可以编写 3 4 +
.
Reverse Polish Notation is a specific way of writing expressions where first you write the values, then the operation you want to perform. So for instance, to add the numbers 3 and 4 you'd write 3 4 +
.
因此要编写 RPN 计算器,您需要
So to write an RPN calculator you'll need
然后循环本质上变成:
while (there's a token available) {
token = get_the_token
if (token is known operator) {
get the number of values from stack this operation requires (usually two); fail if stack doesn't have enough
perform operation on values
push result on the stack
}
else if (token is valid value) {
push it on the stack
}
else {
show error: invalid input
}
}
show result remaining on stack
您可以理解为什么 RPN 使编写计算器变得相当容易:您不必担心在它们所操作的值之间使用运算符,并且您不需要像使用更常见的 中缀 符号形式.例如,我们用中缀表示法写 (10 + (4 * 2))/9
,我们用 RPN 写 10 4 2 * + 9/
.您的计算器会像这样处理这些标记:
You can see why RPN makes writing a calcuator fairly easy: You don't have to worry about having operators between the values they operate on, and you don't need parentheses for grouping as you do with the more common infix form of notation. For instance, where we'd write (10 + (4 * 2)) / 9
in infix notation, we'd write 10 4 2 * + 9 /
in RPN. Your calculator would process those tokens like this:
10
:是一个值,入栈4
:是一个值,入栈2
:是一个值,入栈*
:它是一个运算符,将 2 和 4 从堆栈中弹出并相乘 (4 * 2
);将结果 (8) 压入堆栈+
:它是一个操作符,将8和10从堆栈中弹出并相加(10 + 8
);将结果 (18) 压入堆栈9
:是一个值,入栈/
:是一个操作符,将9和18从栈中弹出并相除(18/9
);将结果(2)压入栈中(注意栈顶的值 9,在本例中 —是除数,它下面的下一个值 18 —是被除数)2
10
: It's a value, push it on the stack4
: It's a value, push it on the stack2
: It's a value, push it on the stack*
: It's an operator, pop 2 and 4 off the stack and multiply them (4 * 2
); push the result (8) on the stack+
: It's an operator, pop 8 and 10 off the stack and add them (10 + 8
); push the result (18) on the stack9
: It's a value, push it on the stack/
: It's an operator, pop 9 and 18 off the stack and divide them (18 / 9
); push the result (2) on the stack (note that the value at the top of the stack — 9, in this case — is the divisor, the next value under it — 18 — is the dividend)2