0

これを括弧を受け入れる場所に変換するにはどうすればよいですか。現在使用できるのは 2 + 4 * 7 のようなものだけです。括弧を無視する方法がわからないので、(2 + 3) * 7 のようなものを読み取りますout * + 2 3 7. 何でも助かります。

#include <iostream>
#include <sstream>
#include <stack>
#include <limits>
#include <string>
using namespace std;

int priority(char a)
{
    int temp;

    if (a == '*' || a == '/' || a == '%')
       temp = 2;
    else  if (a == '+' || a == '-')
       temp = 1;
    return temp;
}

//start
int main()
{
    //declare a string called "infix"
    string infix;
    stringstream output;
    stack<char> s1, s2;

    cout << "Enter an arithmetic expression with no perenthesis: " << endl;
    getline(cin, infix);

    //this loops through backwards searching for the operators 
    for(int i = infix.length() - 1; i >= 0; i--)
    {
        //check the input against +,-,/,*,%
        if (infix[i] == '+' || infix[i] == '-' || 
            infix[i] == '*' || infix[i] == '/' || infix[i] == '%')
        {
            while(!s1.empty() && priority(s1.top()) > priority(infix[i]))
            {       
                output << s1.top();
                s2.push(s1.top());
                s1.pop();           
            }

            s1.push(infix[i]);
        }
        // I think i need to add an else if to check for parenthesis
        // not sure how
        else
        {   
            output << infix[i];
            s2.push(infix[i]);
        }
    }

    while(!s1.empty())
    {
        output << s1.top();
        s2.push(s1.top());
        s1.pop();
    }

    cout << "\nAnswer: ";

    while(!s2.empty())
    {
        cout << s2.top();
        s2.pop();
    }

    cout <<"\n\nPress enter to exit" << endl;
}
4

2 に答える 2

2

逆ポーランド記法を探しています

ここに参照があります - http://en.wikipedia.org/wiki/Reverse_polish_notation

それを実装するためのリンクと読み物を入手できます。

ところで - 6502 アセンブラでやらないでください - それは悪夢です!

于 2013-03-29T05:02:12.713 に答える
0

ご指摘のとおり、中置記法から接頭語記法に変換するつもりです。残念ながら、いくつかの括弧をスキップするだけでは、クエストは簡単ではありません。

括弧なしで対処できる接頭表記とは対照的に、中置表記では、実行したい可能な計算を任意に記述する必要があります。

例としてこれを取ります:

(1 + 2) / (3 + 4)

これは次のようにかなりうまく書き留めることができますが、

 / + 1 2 + 3 4

接頭表記では、同じ計算を括弧なしで中置表記で表現する方法はありません。

すべての操作を順番に分析しようとする代わりに、中置表記で文字列の解析ツリーを構築する本格的なパーサーが必要になります。

そうしないと、計算を正しく行う機会がありません。次のようなことを考えてください

  (1 + 2 * ( 3 / (4 + 3) * 48 + (81 / 4)) + 8) - 9

例えば。

あなたの質問に関連する、調査したい用語は通常、式文法と呼ばれます。

たとえば、ここを見てください: (参照: http://en.wikipedia.org/wiki/Parsing_expression_grammar )

于 2013-03-29T05:12:15.023 に答える