0

作业:对于这个作业,你要编写一个程序,计算用户提供的逆波兰表达式的结果。

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

运算符过多 (+ - / *)

操作数过多(双精度数)

被零除

该程序将接受一个波兰表达式,该表达式将运算符和操作数用一个空格分隔,并以等号结束表达式。

程序将继续获取和评估表达式,直到用户在一行中输入零 (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;
        }
    }
}
4

0 回答 0