开发者

Calculator stack

开发者 https://www.devze.com 2022-12-16 09:30 出处:网络
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

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 开发者_JAVA百科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]?


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,

                    Reg1     Reg2 (Accumulator)  Operator
Input 1                         1
Input +                         1                  +
Input 2               2         1                  +
Enter                 2         3                  +
Enter                 2         5                  +
Enter                 2         7                  +

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.


There is an excellent description and tutorial of the Shunting-yard algorithm (infix -> rpn conversion) on wikipedia.

0

精彩评论

暂无评论...
验证码 换一张
取 消