Print Page Print Page

Ch2 – Floating Point Numbers

  1. Open the Interactions Pane in DrJava.
  2. Type the following and note the results.
> double pi;
> pi = 3.141558;
> pi
3.141558
  1. Type the following in DrJava and note the results.
> double minute = 59.0;
> System.out.println("Fraction of the hour that has passed: ");  
> System.out.println(minute/60.0);
Fraction of the hour that has passed: 
0.9833333333333333
  1. Type the following and note the error.
> double y = 1/3;
> y
0.0

As the text discusses, this is a common error made by developers. The expression interprets the right as dividing two integers and therefore yields an integer result. However, Java does not round a double to an integer, but rather, drops the decimal part and so the result becomes zero.

  1. Modify the previously typed statements to the following and note the correct result.
> double y = 1.0/3.0;
> y
0.3333333333333333