arithmetic operations

closed account (G1pE3TCk)
hey guys, I am having some issues understanding how C++ organizes arithmetic codes. I recently had a quiz in my C++ course and did absolutely horrible on. If any of you could walk me through the logic of the following, it would be greatly appreciated.

3 / 2.0 + 11 / 2 + 5 % 2 = ?

5 / 4 * 3 * 2 / 6 * 8.0 = ?

3.0 / 4 – 2 * 3 = ?

15 * 4 / 8 % 5 * 3 = ?

(( x = 10 ) && (y = 0)) = ?
In order to make sense of expressions like this, there are several rules to follow. One is that an expression is mostly evaluated from left to right. However operator precedence needs to be taken onto account. The main one to remember is that multiplication and division take precedence over addition and subtraction.

Thus the first one: 3 / 2.0 + 11 / 2 + 5 % 2
has the same meaning as (3 / 2.0) + (11 / 2) + (5 % 2)
But we also need to consider that some operations use floating-point values (such as 123.456,while others use integers only, such as 123.

Thus the first example is evaluated like this:
(3 / 2.0) = 1.5 (floating point divide)
(11 / 2) = 5 (integer divide)
(5 % 2) = 1 (integer remainder)
and the final result is 1.5 + 5 + 1 = 7.5

See "Precedence of operators" on this page, http://www.cplusplus.com/doc/tutorial/operators/
Topic archived. No new replies allowed.