【问题标题】:How can I accept negative values in Postfix and Infix Notation?如何接受 Postfix 和 Infix Notation 中的负值?
【发布时间】:2017-03-26 00:31:03
【问题描述】:

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

这两种方法都允许多位整数以及数字输入类型的浮点数。

现在我的问题是:

我想在这两种方法中都包含负输入,例如中缀:“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 3 5 - * == 1 * (3 - 5) == -2) 或否定 (1 3 5 - * + == 1 + (3 * -5) == -14)。最简单的解决方案是不要重载-,并使用不同的字符(可能是~)来明确表示否定。
  • 只是符号的问题;重载 '-' 表示减法和否定。就个人而言,我会简单地使用另一个符号来表示否定(如果你真的必须支持重载,也许还可以使用预先的语法映射传递)。

标签: c++ calculator postfix-notation infix-notation


【解决方案1】:

我没有适合您的完整解决方案,但这里有一些提示。

  1. 我建议在尝试理解操作顺序之前插入一个读取字符并生成标记的抽象层。表达式“(42 + 1) - -3”将变成列表 { '(', 42, '+', 1, ')', '-', '-', 3 }。令牌通常实现为具有枚举类型(例如,OPERATOR 或 NUMBER)和值(例如,字符或浮点数)的类。 (高级:然后您可以将标记转换为表达式树,但这在这里可能不是必需的。)这需要更多的工作,但它比直接字符串解析更容易理解。

    李>
  2. 完成此操作后,关键是确定“-”符号是用作中缀减法还是用作前缀否定。为此,请查看前一个令牌(如果有)。如果它是表达式终止符,例如 ')' 或数字,则它是中缀减法。如果没有这样的token,或者是其他token,就是前缀否定。

【讨论】:

    【解决方案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 函数。但我想,你会自己解决的:)

    快乐编码:)

    【讨论】:

    • 您可能还想看看 cpp 中的 istringstream 类
    猜你喜欢
    • 2021-09-04
    • 2018-09-11
    • 2019-11-30
    • 2021-06-27
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    相关资源
    最近更新 更多