<<< Precedence of Operators, cont. | Index | Increment and Decrement Operators >>> |
Code that calculates a discounted price using the default order of precedence:
double discountPercent = .2; // 20% discount double price = 100; // $100 price price = price * 1 - discountPercent; // price = $99.8
The above formula is incorrect, because multiplication has higher precedence than addition.
Using parentheses that specify the order of precedence remedies the problem:
price = price * (1 – discountPercent); // price = $80
<<< Precedence of Operators, cont. | Index | Increment and Decrement Operators >>> |