0

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.

3
Contributors
3
Replies
16
Views
3 Years
Discussion Span
Last Post by mythos061
0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.