如何在后缀和中缀表示法中接受负值?

How can I accept negative values in Postfix and Infix Notation?

本文关键字:表示 后缀 中缀      更新时间:2023-10-16

我已经为计算器编写了一些方法。一个对输入的后缀表达式求值,另一个将输入的中缀表达式转换为后缀表达式。

这两种方法都允许多位数整数和浮点数作为数字输入类型。

现在是我的问题:

我想在这两种方法中都包含负输入,例如中缀:"3 *(-1)"。

然而,我对如何实现这个问题有点缺乏想法。也许有人可以给我的想法或代码示例。

我在下面包括了这两个方法。其中使用了一些简单的方法,这里没有显示,但大多数函数名应该能很好地解释它们。由于这个事实,我省略了它们,以使内容尽可能简短。

string InfixToPostfix(string expression)
{
    string postfix = "";
    stack <char> S;
    for (int i = 0; i < expression.length(); i++)
    {
        if (expression[i] == ' ') continue;                             // Falls leerzeichen oder ',' gefunden mit nächster Iteration weiter machen
        else if (IsOperator(expression[i]))                                                     // Falls ein Operator gefunden wurde:
        {
            while (!S.empty() && S.top() != '(' && HasHigherPrecedence(S.top(), expression[i]))     // Wenn Operator auf Stack höhere Precedence hat, dann diesen an String anhängen und vom Stack nehmen
            {
                postfix += S.top();
                postfix += ' ';
                S.pop();
            }
            S.push(expression[i]);                                                                  // Wenn Operator die Bedingungen in der while Schleife nicht erfüllt diesen auf Stack legen
        }
        else if (isDigit(expression[i]) || isComma(expression[i]))                                                      //Wenn ein Digit gefunden wurde diesen an String anhängen
        {
            postfix += expression[i];
            if (i+1 >= expression.length() || (!isDigit(expression[i + 1]) && !isComma(expression[i+1])))                   //Wenn die nächste Zahl kein Digit ist, dann leerzeichne an String anhängen
            {
                postfix += ' ';
            }
        }
        else if (expression[i] == '(')                                                          // '(' wird auf Stack gepusht
        {
            S.push(expression[i]);
        }
        else if (expression[i] == ')')                                                          // Wenn ')' gefunden wird, dann:
        {
            while (!S.empty() && S.top() != '(')                                                    // Sofern Stack nicht leer und das oberste Element des Stacks nicht eine Klammer auf ist wird das oberste Element des Stacks dem String angehängt
            {
                postfix += S.top();
                S.pop();
            }
            S.pop();                                                                                //ansonsten wird '(' einfach vom Stack genommen
        }
    }
    while (!S.empty())                                                                          // Am Ende der Expression werden alle verbleibenden Elemente vom Stack genommen und Leerzeichen eingefügt
        {
            postfix += S.top();
            postfix += ' ';
            S.pop();
        }
    return postfix;                                                                             // Rückgabe der jetzt in Postfix vorliegenden Expression
}
//Löst eine Aufgabe in Postfix Notation
float EvaluatePostfix(string expression)    
{
    stack<float> S;
    float j;

    for (int i = 0; i< expression.length(); i++) {
        if (expression[i] == ' ') continue;                                 // wenn leer oder ',' mit nächster iteration weiter machen
        else if (IsOperator(expression[i])) {                                       //Wenn Operator nehme die Operanden vom Stack und wende den Operator an
            float operand2 = S.top(); 
            S.pop();
            float operand1 = S.top(); 
            S.pop();
            float result = PerformOperation(expression[i], operand1, operand2);
            S.push(result);                                                         //Das Ergebnis zurück auf Stack legen
        }
        else if (isDigit(expression[i])) 
        {
            float operand = 0;
            while (i<expression.length() && isDigit(expression[i])) 
            {
                operand = (operand * 10) + (expression[i] - '0');                   //wenn rechts einer Zahl eine weitere Zahl steht, kann operand mal 10 genommen werden und die rechts stehende zahl addiert werden
                i++;
            }
            if (i < expression.length() && isComma(expression[i]))
            {
                j = 1.0;
                i++;
                while (i < expression.length() && isDigit(expression[i]))
                {
                    operand = operand + ((expression[i] - '0') / pow(10.0, j));
                    i++;
                    j++;
                }
            }
            i--;                                                                    //Verhindert einen Skip des Operators, i wird sowohl in der while schleife als auch im for hochgezählt
            S.push(operand);                                                        //Der Operand wird auf den Stack gepusht
        }
    }
    return S.top();                                                                 //Stack sollte ein element besitzen, somit ist dies das Ergebnis
}

我没有一个完整的解决方案,但这里有一些技巧。

  1. 我建议在尝试理解操作顺序之前插入一个读取字符并产生令牌的抽象层。表达式"(42 + 1)- 3"将成为{"(列表",42岁,"+"1 , ')', '-', '-', 3}。令牌通常被实现为具有enum类型(例如OPERATOR或NUMBER)和值(例如char或float)的类。(高级:然后您可以将标记转换为表达式树,但这里可能不需要这样做。)这需要多做一些工作,但与直接字符串解析相比,它使事情更容易理解。

  2. 一旦你这样做了,关键是确定'-'符号是打算作为中缀减法还是作为前缀否定。要做到这一点,请查看之前的令牌(如果有的话)。如果它是一个表达式结束符,如')'或一个数字,它是中缀减法。如果没有这样的令牌,或者是其他令牌,则前缀否定。

我是这样做的:

class expression
{
    //constructors and destructors
public:
    expression();
    ~expression();
    //member properties
private:
    std::string expr;
    std::string postfixExpr;
    //member methods
public:
    // accepts the expression from the user
    void input();
    //prints the accepted expression
    void output();
    //evaluates the accepted expression
    float eval();
    //converts infix expression to postfix
    void convertToPostfix();
    friend bool isOperator(char);
};
inline bool isOperator(char c)
{
    if (c == '+' || c == '-' || c == '*' || c == '/' || c == '(' || c == ')' || c == '#')
        return true;
    return false;
}
void expression::input()
{
    std::cin >> this->expr;
}
float expression::eval()
{
    std::stack<float> s;
    float op1, op2;
    for (int i = 0; i < expr.length(); i++)
    {
        if (expr[i] == '(')
        {
            float sum = 0;
            bool flag = false;
            while (expr[++i] != ')')
            {
                if (expr[i] == '-') {
                    flag = true;
                    i++;
                }
                sum = sum * 10.0 + (float(expr[i]) - float('0'));
            }
            if (flag)
                sum = -sum;
            s.push(sum);
            continue;
        }
        else if (!isOperator(expr[i]))
        {
            s.push(float(expr[i]) - float('0'));
        }
        else
        {
            op2 = s.top();
            s.pop();
            op1 = s.top();
            s.pop();
            switch (expr[i])
            {
            case '+':
                s.push(op1 + op2);
                break;
            case '-':
                s.push(op1 - op2);
                break;
            case'*':
                s.push(op1*op2);
                break;
            case '/':
                s.push(op1 / op2);
                break;
            default:
                std::cerr << "Wrong operator" << std::endl;
                return 0;
            }
        }
    }
    return s.top();
}

在我的实现中,唯一的问题是使用'('和')'作为分隔符。其次,我还将std::string expr作为表达式类中的一个属性。这很好。但是请注意,一定要用后缀表示法输入表达式,因为我仍然必须包含convertToPostfix函数。但是我想,你会自己弄明白的:)

Happy Coding:)