Java Reference
In-Depth Information
System.out.print("Your average score is ");
System.out.println(average);
What could be wrong with that? Of course, the average of s1, s2 , and s3 is
s 1
+
s 2
+
s 3
3
Here, however, the / does not mean division in the mathematical sense. It denotes
integer division, because the values s1 + s2 + s3 and 3 are both integers. For
example, if the scores add up to 14, the average is computed to be 4, the result of
the integer division of 14 by 3.
151
152
That integer 4 is then moved into the floating-point variable average. The remedy
is to make either the numerator or denominator into a floating-point number:
double total = s1 + s2 + s3;
double average = total / 3;
or
double average = (s1 + s2 + s3) / 3.0;
C OMMON E RROR 4.2: Unbalanced Parentheses
Consider the expression
1.5 * ((-(b - Math.sqrt(b * b - 4 * a * c)) / (2 *
a))
What is wrong with it? Count the parentheses. There are five opening parentheses (
and four closing parentheses ). The parentheses are unbalanced. This kind of
typing error is very common with complicated expressions. Now consider this
expression.
1.5 * (Math.sqrt(b * b - 4 * a * c))) - ((b / 2 *
a))
This expression has five opening parentheses ( and five closing parentheses ), but
it is still not correct. In the middle of the expression,
1.5 * (Math.sqrt(b * b - 4 * a * c))) - ((b / (2 *
a))
 
Search WWH ::




Custom Search