[英]C++ Calculator using Stacks and Queues
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
Can only mean 只能意味着
((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: 至于实现:如果你有一个堆栈,你可以按如下方式处理上面的表达式:
+
(an operation), push it onto the stack, +
(操作),将其推入堆栈, *
(an operation), push it onto the stack, *
(操作),将其推入堆栈, -
(an operation), push it onto the stack, -
(操作),将其推入堆栈, 4
(a number), the top of the stack is not a number, so push it onto the stack. 4
(数字),堆栈顶部不是数字,所以将其推入堆栈。 2
(a number), the top of the stack is a number, so pop from the stack twice, you get 4 - 2
, calculate it ( 2
), and push the result ( 2
) onto the stack. 2
(一个数字),堆栈的顶部是一个数字,因此从堆栈弹出两次,得到4 - 2
,计算它( 2
),并将结果( 2
)推入堆栈。 5
(a number), the top of the stack is a number, so pop from the stack twice, you get 2 * 5
, push the result ( 10
) onto the stack. 5
(数字),堆栈的顶部是一个数字,因此从堆栈弹出两次,得到2 * 5
,将结果( 10
)推入堆栈。 3
(a number), the top of the stack is a number, so pop from the stack twice, you get 3 + 10
, push the result ( 13
) onto the stack. 3
(数字),堆栈的顶部是一个数字,因此从堆栈中弹出两次,得到3 + 10
,将结果( 13
)推入堆栈。 13
). 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. 正如您所看到的,表达式是使用一些简单的规则进行评估的,无需在整个字符串中搜索括号或必须确定乘法是否优先于加法和减法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.