postfix-ausdruck berechnen



  • hallo zusammen!

    ich habe einen infix-ausdruck mit dem u.a. Programm in einen Postfix-Ausdruck umgewandelt. Wie muss ich jetzt vorgehen, damit ich den ausgegebenen Postfix-Audruck berechnen kann, angenommen dieser besteht nur aus ganzzahligen Zeichen (und eben den Operatoren)? Ist das schwierig?

    Vielen Dank!!

    #include <iostream.h>
    #include <iomanip.h>
    #include <stack.h>
    #include <string.h>
    
    using namespace std;
    
    bool praezedenzCheck (char zeichen1, char zeichen2);
    void convert (const string& infix, string& postfix);
    bool zeichenCheck (char zeichen);
    string stackAusgabe(string postfix);
    
    bool zeichenCheck (char zeichen)
    {
      if (( zeichen == '+') || (zeichen == '*') || (zeichen == '-')
        ||  ( zeichen == '/') || (zeichen == '(') || (zeichen == ')'))
        return false;
      else
        return true;
    }
    
    bool praezedenzCheck (char zeichen1, char zeichen2)
    {
      if ((zeichen1 == '(') || (zeichen2 == '('))
        return false;
      if ((zeichen2 == ')') || (zeichen1 == '*') || (zeichen2 == '/'))
        return true;
      if ((zeichen2 == '*') || (zeichen1 == '/') || (zeichen1 == '+') || ( zeichen2 == '-'))
        return false;
      else
        return true;
    }
    
    void convert (const string& infix, string& postfix)
    {
      stack <char> postfixStack;
        char symbol, topsymbol;
        for ( int i = 0; i < infix.size(); i ++)
          {
          symbol = infix[i];
          if (zeichenCheck(symbol))
            postfix = postfix + symbol;
          else
            {
            while (( ! postfixStack.empty()) && (praezedenzCheck(postfixStack.top() , symbol)))
              {
              topsymbol = postfixStack.top();
              postfixStack.pop();
              postfix = postfix + topsymbol;
              }
    
            if ((! postfixStack.empty()) && (symbol == ')'))
              postfixStack.pop();
            else
              postfixStack.push(symbol);
            }
          }
    
        while (! postfixStack.empty())
          {
          topsymbol = postfixStack.top();
          postfixStack.pop();
          postfix = postfix + topsymbol;
          }
    }
    
    string stackAusgabe(string postfix)
      {
        cout << endl << endl << "Ausdruck in Postfix-Notation lautet: " << postfix << endl << endl;
      }
    
    int main()
      {
      int integer = 0;
        while (integer == 0)
        {
        string  infix,postfix;
        cout << endl << endl << "Arithmetischen Ausdruck in Infix-Notation eingeben: ";
        cin >> infix;
        convert (infix, postfix);
        stackAusgabe(postfix);
        }
      return 0;
      }
    

Anmelden zum Antworten