如何使用多个运算符解决反向抛光表示法?

时间:2017-04-14 02:21:14

标签: c++ arrays stack conditional break

https://en.wikipedia.org/wiki/Reverse_Polish_notation

我正在尝试使用我创建的堆栈类在C ++中解决反向抛光表示法。如果只有一个操作符,我的代码可以正常工作。

3
5 5 +
5 5 *
5 10 * 5 +

这些输入会给我结果

10 25 50

正如你所看到的,前两个是正确的,但最后一个只有5 * 10.它不会在50中加5.我相信它是因为我在条件结束时打破了,但如果我删除它们,我的循环无限地继续。任何关于如何解决这个问题的建议将不胜感激。

我的代码:

#include "stdafx.h"
#include "stack.h"
#include <string>
#include <iostream>
#include <sstream>
#include "string.h"

using namespace std;

int main()
{
    stack stackname;
    string command;
    int temp;
    int temp2;
    int answer;
    int count;
    cin >> count;


    while (count > 0)
    {
        while (cin >> command)
        {
            if (command != "+" && command != "-" && command != "/" && command != "*")
            {
                int stringtonum = stoi(command);
                stackname.push(stringtonum);
            }
            else if (command == "+")
            {
                temp = stackname.pop();
                temp2 = stackname.pop();
                answer = temp + temp2;
                stackname.push(answer);
                break;
            }
            else if (command == "-")
            {
                temp = stackname.pop();
                temp2 = stackname.pop();
                answer = temp2 - temp;
                stackname.push(answer);
                break;
            }
            else if (command == "/")
            {
                temp = stackname.pop();
                temp2 = stackname.pop();
                answer = temp2 / temp;
                stackname.push(answer);
                break;
            }
            else if (command == "*")
            {
                temp = stackname.pop();
                temp2 = stackname.pop();
                answer = temp * temp2;
                stackname.push(answer);
                break;
            }
        }
        count = count - 1;
    }

    stackname.showStack();
    system("pause");
}

1 个答案:

答案 0 :(得分:0)

尝试一次性实现所有内容都被认为是一个新手的错误,因为你会立刻调试一切而淹没。建议:实现循环和输入为&#34; abstract&#34;调用函数执行测试的程序。让功能变得愚蠢&#34;插头&#34;直到该包装器变得起作用(例如,函数将只打印从程序接收的内容)。接下来实现测试本身。这种方法也会阻止代码审阅者被两个任务融合。这是经验法则之一:将代码划分为对其功能不利的区域。

为什么你要使用自定义堆栈?你的代码也可能在那里失败,所以首先测试你自制的堆栈。如果您被允许使用std ::,则会有std :: deque提供堆栈功能。对于较新的编译器,std :: stack是std :: deque的便利包装器(但也可以使用其他东西作为容器)。您可以使用标准堆栈测试RPN循环,然后替换为您的RPN循环。至于算法,它应该模拟复古(手持?)计算器算法:

  1. 读取令牌(循环开始)
  2. if token - 数值,推入堆栈
  3. 如果是令牌 - 操作,检查堆栈是否有足够的值用于适当的参数计数。也可能有一元行动(一元减去是一个例子),或者甚至可能是三元?
  4. 如果(3)输出错误状态失败,则break,否则弹出值并执行操作
  5. 如果(4)成功,将结果推入堆栈并continue否则输出错误状态和break