C++ newbie: order of operations for * and /?

Antst

New member
Jul 29, 2010
24
0
1
Hello all:

Does anyone know what the order of operations would be for these expressions (below)? I have tried googling, but am still confused. I'm trying to figure out why my code results are weird and I suspect my problem is related to this...

(1)
x = y / ( z ) * 1.0e-3;

(2)
x = y / ( z * 1.0e-3);

Thanks a lot.
 
The general laws of mathematics apply to most high-level programming languages, including C++, C#, Java, Perl, Python, etc.

The easiest way to remember it is by this acronym: BIMDAS

B //brackets always have priority, and as such are calculated first. Brackets inside of brackets are then again of higher priority, and this can regress infinitely.

I //indices; that is, powers, squares, square-roots, cubes, always have second priority

MD //multiplication and division. These are of the same priority, and are always calculated before addition and subtraction

AS //addition and subtraction - these are the last to be calculated

If there are two operands of equal priority in the same expression, they will usually be calculated left-to-right.

E.g.
2^2 * (4 * 3 / 2) + 55
= 4 * (12/2) + 55
= 4 * 6 + 55
= 24 + 55
= 79

For your two expressions:

(1) x = y / (z) * 1.0e-3
is equivelent to: x = (y/z)*(1.0e-3)

(2) x = y/(z*1.0e-3)
is equivelent to: x=(y) / (z*(1.0e-3))
 
In math, both should lead to the same result.
In C or C++, you should take care if both y and z are integers. for example
5 / 2 = 2
In this case
x = y / ( z ) * 1.0e-3;
and
x = y / ( z * 1.0e-3);
might not the same!!
 
1. x is y divided by z, that result multiplied by 1e-3.

2. z multiplied 1.0e-3, y divided by that result, is x.
 
Back
Top