Sams Teach Yourself C in 21 Days

(singke) #1
12: System.out.println(“Adding two numbers: “);
13: System.out.print(“ The sum of 1.4 and 6.7 is “);
14: d = MyClass.sumOf(1.4, 6.7);
15: System.out.println(Double.toString(d));
16: System.out.println(“Adding three numbers: “);
17: System.out.print(“ The sum of 1.4, 6.7, and 12.2 is “);
18: d = MyClass.sumOf(1.4, 6.7, 12.2);
19: System.out.println(Double.toString(d));
20: System.out.println(“Adding four numbers: “);
21: System.out.print(“ The sum of 1.4, 6.7, 12.2, and -4.1 is “);
22: d = MyClass.sumOf(1.4, 6.7, 12.2, -4.1);
23: System.out.println(Double.toString(d));
24: }
25: }

Adding two numbers:
The sum of 1.4 and 6.7 is 8.1.
Adding three numbers:
The sum of 1.4, 6.7, and 12.2 is 20.299999999999997
Adding 4 numbers:
The sum of 1.4, 6.7, 12.2, and -4.1 is 16.199999999999997
In the first listing, the code for the class Overloadedis quite simple. Lines 3 to 5
define one sumOfmethod, taking two type doublearguments. Lines 7 to 9 and 11
to 13 define the other two sumOfmethods, one taking three and the other taking four type
doublearguments. Within each method, the code simply adds the arguments together
and returns the result.
Lines 1 and 2 of OverloadDemo import two Java classes the program uses. Lines 8 and 9
declare the two variables that are required, and line 11 creates an instance of the
Overloadedclass. Lines 12–13 display some explanatory text on the console. Line 14
uses the sumOfmethod to add two numbers, and line 15 displays the result on the screen.
Lines 16 to 19 and 20 to 23 repeat the same process for three and four numbers, respec-
tively.

732 Bonus Day 5

LISTINGB5.6 continued

OUTPUT

ANALYSIS

In the output from this example, note that the second and third answers are
not perfectly accurate. This occurs because the way in which a computer
stores floating point numbers makes it impossible to accurately represent
certain values. The very minor loss in accuracy that results is meaningless for
most applications.

Caution


40 448201x-Bonus5 8/13/02 11:23 AM Page 732

Free download pdf