Symbol | Operation |
---|---|
+ | Add |
- | Subtract |
* | Multiply |
/ | Divide |
% | Remainder (Modulo) |
Expression Evaluates to --------------- ------------------ 2 + 3 * 4 = 2 + (3 * 4) * before + = 2 + 12 = 14 |
Expression Evaluates to --------------- ------------------ 2 - 3 - 4 * 5 = 2 - 3 - (4 * 5) * before + = (2 - 3) - 20 left to right = -1 - 20 = -21 |
Expression Evaluates to --------------- ------------------ 2 - (3 - 4) * 5 = 2 - (-1) * 5 () overrides = 2 - (-1 * 5) * before + = 2 - -5 = 7 |
Expression Evaluates to --------------- ------------------ 2 + 2.0 = 2.0 + 2.0 (convert int to double) = 4.0 |
except in the following case...
The remainder of the division is discarded !!!
Expression Evaluates to --------------- ------------------ 7 / 4 1 (7 / 4 = 1 with remainder 3 the remainder is discarded) |
Expression Evaluates to --------------- ------------------ 7.0 / 4.0 1.75 (Floating point division works like a calculator !!!) |
Expression Evaluates to --------------- ------------------ 7.0 / 4 = 7.0 / 4.0 (convert integer to floating point !) = 1.75 |
In other words, both operands in the remainder operator (%) operation must be integers.
Expression Evaluates to --------------- ------------------ 7 % 4 3 (7 / 4 = 1 with remainder 3 The answer is the remainder) |
double average = s1 + s2 + s3 / 3;
The expression computes:
double average = s1 + s2 + (s3 / 3);
double average = (s1 + s2 + s3) / 3;
Case in point: (1 + 1 + 3) / 3 = 5 / 3 = 1
The correct answer is 1.6666666666666
The correct way to write the expression for average is:
double average = (s1 + s2 + s3) / 3.0 ;
You must use 3.0 to avoid integer division !!!