使用堆栈和队列的C ++计算器 [英] C++ Calculator using Stacks and Queues

查看:171
本文介绍了使用堆栈和队列的C ++计算器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在课堂上理解一个有关使用堆栈和队列作为对计算器进行编程的方法的主题。我了解什么是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:


  1. 读取 + (一个操作),将其压入堆栈,

  2. 读取 * (操作),将其压入堆栈,

  3. 读取-(操作),将其压入堆栈,

  4. 读取 4 (一个数字),堆栈的顶部不是数字,因此将其压入堆栈。

  5. 读取 2 (一个数字),堆栈的顶部是一个数字,因此从堆栈中弹出两次,得到 4-2 ,c将其计算( 2 ),然后将结果( 2 )压入堆栈。

  6. 读取 5 (一个数字),堆栈的顶部是一个数字,因此从堆栈中弹出两次,得到 2 * 5 ,将结果( 10 )压入堆栈。

  7. 读取 3 (一个数字),堆栈顶部是一个数字,因此从堆栈中弹出两次,得到 3 + 10 ,然后按结果( 13 )放到堆栈上。

  8. 没什么可读取的,从堆栈中弹出并返回结果( 13 )。

  1. Read + (an operation), push it onto the stack,
  2. Read * (an operation), push it onto the stack,
  3. Read - (an operation), push it onto the stack,
  4. Read 4 (a number), the top of the stack is not a number, so push it onto the stack.
  5. Read 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.
  6. Read 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.
  7. Read 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.
  8. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆