使用堆栈和队列的C ++计算器 [英] C++ Calculator using Stacks and Queues
问题描述
我试图在课堂上理解一个有关使用堆栈和队列作为对计算器进行编程的方法的主题。我了解什么是infix和postfix表达式,但是它如何使程序更易于评估表达式以及为什么在这种情况下队列和堆栈是理想的?谢谢
I'm trying to understand a topic in class about using stacks and queues as a means of programming a calculator. I understand what infix and postfix expression is but how does it make it easier for a program to evaluate an expression and why are queues and stacks ideal in this situation? Thanks
推荐答案
它使操作顺序更易于处理,例如:
It makes the order of operations simpler to handle, for example:
+ * - 4 2 5 3
可以仅表示
((4 - 2) * 5) + 3
对于我们来说,这可能更易读,但我们需要知道操作的顺序并匹配括号以找出答案。
Which might be more readable for us, but we need to know the order of operations and match parentheses to figure it out.
关于实现:如果有一个堆栈,则可以按以下方式处理上面的表达式:
As for implementing: if you had a stack, you could handle the expression above as follows:
- 读取
+
(一个操作),将其压入堆栈, - 读取
*
(操作),将其压入堆栈, - 读取
-
(操作),将其压入堆栈, - 读取
4
(一个数字),堆栈的顶部不是数字,因此将其压入堆栈。 - 读取
2
(一个数字),堆栈的顶部是一个数字,因此从堆栈中弹出两次,得到4-2
,c将其计算(2
),然后将结果(2
)压入堆栈。 - 读取
5
(一个数字),堆栈的顶部是一个数字,因此从堆栈中弹出两次,得到2 * 5
,将结果(10
)压入堆栈。 - 读取
3
(一个数字),堆栈顶部是一个数字,因此从堆栈中弹出两次,得到3 + 10
,然后按结果(13
)放到堆栈上。 - 没什么可读取的,从堆栈中弹出并返回结果(
13
)。
- Read
+
(an operation), push it onto the stack, - Read
*
(an operation), push it onto the stack, - Read
-
(an operation), push it onto the stack, - Read
4
(a number), the top of the stack is not a number, so push it onto the stack. - Read
2
(a number), the top of the stack is a number, so pop from the stack twice, you get4 - 2
, calculate it (2
), and push the result (2
) onto the stack. - Read
5
(a number), the top of the stack is a number, so pop from the stack twice, you get2 * 5
, push the result (10
) onto the stack. - Read
3
(a number), the top of the stack is a number, so pop from the stack twice, you get3 + 10
, push the result (13
) onto the stack. - Nothing left to read, pop from the stack and return the result (
13
).
如您所见,表达式是使用一些简单规则求值的不必在整个字符串中搜索括号,也不必决定乘法是否优先于加法和减法。
So as you can see, the expression was evaluated using a few simple rules and without having to search through the entire string for parentheses or having to decide whether multiplication has priority over addition and subtraction.
这篇关于使用堆栈和队列的C ++计算器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!