I know how to convert from infix to prefix or postfix. But how do you wrap parentheses around this problem:

a / b * c - d + e * f + g

This is how I think it is accomplished:

( ( ( a / b ) * c ) - d ) + ( ( e * f ) + g )

Am I doing something wrong? I am wraping parentheses around terms left to right using P E MD AS.

Recommended Answers

All 3 Replies

There is a "natural" order of precidence for math operators, some of which have the same precidence. IE: / and * are higher than + or -. Using parens is a way to specify your own. So do it in the way that you want to guarantee the order of evaluation to take place. IE, you may want this instead:

(a / (b * c)) - ((d + e) * (f + g))

In this case, it will multiply b by c, then divide a by that result, then it will add d and e, and multiply that by f plus g, and subtract the result of that from the first part. IE: it is the same as this:

    x1 = b * c;
    x2 = a / x1;
    y1 = d + e;
    y2 = f + g;
    z1 = y1 * y2;
    z2 = x1 - z1;

Where you put your parens is important. Both of your results evaluate the same (33 for integers, and 34.5 for floats). Changing the parens as I did results in -111 for both integer and floaing point values.

To do this programatically you would create an expression tree and traverse that placing parenthesis around each operation.

Thank you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.