`Div1' example program: demonstrates how to avoid the pitfall of integer division

Div1.java

// Div1.java
// A program that works out 2/5.  
// Kevin Boone, May 1999

import java.applet.Applet;
import java.awt.*;

public class Div1 extends Applet
{
public void paint (Graphics g)
	{
	// Note that not only must the result be stored in a 
	//  variable of type ``double'', (or ``float'', but not
	//  ``int'', the numbers have to be given as 2.0 and
	//  5.0, not 2 and 5. The problem is that the computer only
	//  does one thing at a time. If I say `2/5', it does the
	//  division using whole numbers (integers), then puts the
	//  result into the variable `result'. But by then it is too	
	//  late: the decimal part has already been lost. By saying
	//  2.0 and not 2, the Java compiler knows that it has to 
	//  do the calculation using the decimal part as well!

	double result = 2.0 / 5.0; 
	
	g.drawString ("2 / 5", 20, 20);

	g.drawString (Double.toString(result), 20, 40);
	}
}


©1994-2003 Kevin Boone, all rights reserved