计算器堆栈
我对计算器的理解是它们是基于堆栈的。当您使用大多数计算器时,如果您输入 1 + 2 [enter] [enter]
,您会得到 5
。 1
被压入堆栈,+
是运算符,然后 2
被压入堆栈。第一个 [enter]
应该将 1
和 2
从堆栈中弹出,将它们添加到 3
然后压入 < code>3 返回堆栈。第二个 [enter]
不应该访问 2
,因为它实际上不存在于任何地方。
如何保留 2
以便第二个 [enter]
可以使用它?
2
是在 3
之前被推回堆栈还是保留在其他地方供以后使用?如果它被推回到堆栈上,您可以想象通过重复执行[operator] [number] [enter] [enter]
会导致堆栈溢出吗?
My understanding of calculators is that they are stack-based. When you use most calculators, if you type 1 + 2 [enter] [enter]
you get 5
. 1
is pushed on the stack, +
is the operator, then 2
is pushed on the stack. The 1st [enter]
should pop 1
and 2
off the stack, add them to get 3
then push 3
back on the stack. The 2nd [enter]
shouldn't have access to the 2
because it effectively doesn't exist anywhere.
How is the 2
retained so that the 2nd [enter]
can use it?
Is 2
pushed back onto the stack before the 3
or is it retained somewhere else for later use? If it is pushed back on the stack, can you conceivably cause a stack overflow by repeatedly doing [operator] [number] [enter] [enter]
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
从概念上讲,在硬件中,这些值被放入寄存器中。在简单的 ALU(算术逻辑单元(即简单的 CPU))中,寄存器之一将被视为累加器。您正在讨论的值可以放在堆栈上进行处理,但是一旦堆栈为空,寄存器值(包括最后一个操作)可能会缓存在这些寄存器中。当被告知再次执行操作时,使用累加器以及最后一个参数。
例如,
所以它可能是所使用的硬件的函数。
Conceptually, in hardware these values are put into registers. In simple ALU (Arithmatic Logical Units (i.e. simply CPUs)), one of the registers would be considered an accumulator. The values you're discussing could be put on a stack to process, but once the stack is empty, the register value (including the last operation) may be cached in these registers. To which, when told to perform the operation again, uses the accumulator as well as the last argument.
For example,
So it may be a function of the hardware being used.
唯一真正的基于堆栈的计算器是以逆波兰表示法作为输入方法的计算器,因为该表示法直接在堆栈上运行。
The only true stack based calculators are calculators which have Reverse Polish Notation as the input method, as that notation directly operates on stacks.
您需要做的就是保留最后一个运算符和操作数,并在堆栈为空时应用它们。
All you would need to do is retain the last operator and operand, and just apply them if the stack is empty.
在 Shunting-yard 算法(中缀 -> rpn 转换)上有一个很好的描述和教程维基百科。
There is an excellent description and tutorial of the Shunting-yard algorithm (infix -> rpn conversion) on wikipedia.