Search

Friday, December 14, 2018

Floating-Point Types

As explained in Module 1, the floating-point types can represent numbers that have fractional components. There are two kinds of floating-point types, float and double, which represent single- and double-precision numbers, respectively. Type float is 32 bits wide and type double is 64 bits wide.

Of the two, double is the most commonly used because all of the math functions in Java’s class library use double values. 
For example,
the sqrt ()method (which is defined by the standard Math class ) returns a double value that is the square root of its double argument. Here, sqrt( )is used to compute the length of the hypotenuse, given the lengths of the two opposing sides:
/*
Use the Pythagorean theorem to find the length of the hypotenuse given the lengths of the two opposing sides.
*/ class Hypot 
public static void main(String args[]) 
double x, y, z;
x = 3; y = 4;
z = Math.sqrt(x*x + y*y);
System.out.println("Hypotenuse is " +z);
}
}
The output from the program is shown here:
Hypotenuse is 5.0
Notice how sqrt( ) is called. It is preceded by the name of the class of which it is a member.
One other point about the preceding example: As mentioned,sqrt( )is a member of the standard Math class. Notice how sqrt( )is called; it is preceded by the name Math. This is similar to the way System. out precedes println( ). Although not all standard methods are called by specifying their class name first, several are. 

0 comments:

Post a Comment