The completed program is given below
public class HarmonicTester { public static void main ( String[] args ) { int term=1, lastTerm = 6; double sum = 0.0; while ( term <= lastTerm ) { sum += 1.0/term; // add the next term to sum term++ ; // increment term } System.out.println("Sum of 6 terms:" + sum ) ; } }
Recall that the expression 1.0/term
is double precision floating point because
the 1.0
is that type.
The expression 1/term
would call for
integer division, and would compute integer zero.
You might wish to copy this program to your editor and run it. If you do, you will see something like:
C:\users>java HarmonicTester Sum of 6 terms:2.4499999999999997
The inaccuracy of floating point resulted in the tail of 9's.
How might this program be improved? Click here for a