用C ++创建反向波兰语计算器

时间:2016-02-27 07:59:06

标签: c++ polish-notation

作业:对于此作业,您将编写一个程序,该程序将计算用户提供的反向波兰语表达式的结果。

您必须处理以下情况(错误):

操作员太多(+ - / *)

操作数太多(双打)

除以零

程序将采用波兰语表达式,将运算符和操作数分隔为单个空格,并使用等号终止表达式。

程序将继续采用并计算表达式,直到用户在一行上输入零(0)后跟一个新行。

  

问题1:我在告诉用户操作员和操作数太多时遇到问题。我试着编码,但我没有   想法从哪里开始。

     

问题2:我希望程序在用户输入0时结束,但是当我在程序中执行此操作时,它没有做任何事情。

#include<iostream>
#include<iomanip>
#include<string>
#include<sstream>

using namespace std;

class Node
{
    double data;
    Node *top;
    Node *ptr;
public:
    Node()
    {
        top = NULL;
        ptr = NULL;
    }

    bool isEmpty()
    {
        return top == 0;
    }

    void pushValue(double val)
    {
        Node *next = new Node;
        next->data = val;
        next->ptr = top;
        top = next;
    }

    double popVal()
    {
        if (isEmpty())
        {
            cout << "Error: Too many operators" << endl;
        }
        else
        {
            Node *next = top->ptr;
            double ret = top->data;
            delete top;
            top = next;
            return ret;
        }

    }
//Displays the answer of the equation
    void print()
    {
        cout << "= " << top->data << endl;
    }
};

bool isOperator(const string& input)
{
    string ops[] = { "+", "-", "*", "/" };
    for (int i = 0; i < 4; i++)
    {
        if (input == ops[i])
        {
            return true;
        }
    }
    return false;
}
//This function tells the operators what to do with the values.
void performOp(const string& input, Node& stack)
{
    double Val1, Val2;
    int errorCheck = 0;

    Val1 = stack.popVal();
    Val2 = stack.popVal();

    if (input == "+")
    {
        stack.pushValue(Val1 + Val2);
    }
    else if (input == "-")
    {
        stack.pushValue(Val1 - Val2);
    }
    else if (input == "*")
    {
        stack.pushValue(Val1 * Val2);
    }
    else if (input == "/" && Val2 != 0)
    {
        stack.pushValue(Val1 / Val2);
    }

    if (input == "/" && Val2 == 0)
    {
        cout << "Error: Division by zero" << endl;
        errorCheck = 1;
    }

    if (errorCheck == 0)
    {
        stack.print();
    }
}

int main()
{
    cout << "Reverse Polish Notation Calculator!" << endl;
    cout << "-------------------------------------------------------------------" << endl;
    cout << "Enter your values followed by your operators(Enter 0 to exit)" << endl;

    string input;
    Node stack;
//Checks the user's input to see which function to use.
    while (true)
    {
        cin >> input;
        double num;

        if (stringstream(input) >> num)
        {
            stack.pushValue(num);
        }
        else if (isOperator(input))
        {
            performOp(input, stack);
        }
        else if (input == "0")
        {
            return 0;
        }
    }
}

0 个答案:

没有答案