Java Reference
In-Depth Information
For example,
Math.ceil( 2.1 ) returns 4.0
Math.ceil( 2.0 ) returns 2.0
Math.ceil( -2.0 ) returns -2.0
Math.ceil( -2.1 ) returns -2.0
Math.floor( 2.1 ) returns 2.0
Math.floor( 2.0 ) returns 2.0
Math.floor( -2.0 ) returns -2.0
Math.floor( -2.1 ) returns -4.0
Math.rint( 2.1 ) returns 2.0
Math.rint( -2.0 ) returns -2.0
Math.rint( -2.1 ) returns -2.0
Math.rint( 2.5 ) returns 2.0
Math.rint( 4.5 ) returns 4.0
Math.rint( -2.5 ) returns -2.0
Math.round( 2.6f ) returns 3 // Returns int
Math.round( 2.0 ) returns 2 // Returns long
Math.round( -2.0f ) returns -2 // Returns int
Math.round( -2.6 ) returns -3 // Returns long
Math.round( -2.4 ) returns -2 // Returns long
4.2.4 The min , max , and abs Methods
The min and max methods return the minimum and maximum numbers of two numbers ( int ,
long , float , or double ). For example, max(4.4, 5.0) returns 5.0 , and min(3, 2)
returns 2 .
The abs method returns the absolute value of the number ( int , long , float , or double ).
For example,
Math.max( 2 , 3 ) returns 3
Math.max( 2.5 , 3 ) returns 4.0
Math.min( 2.5 , 4.6 ) returns 2.5
Math.abs( -2 ) returns 2
Math.abs( -2.1 ) returns 2.1
4.2.5 The random Method
You have used the random() method in the preceding chapter. This method generates a ran-
dom double value greater than or equal to 0.0 and less than 1.0 ( 0 <= Math.random() <
1.0 ). You can use it to write a simple expression to generate random numbers in any range.
For example,
Returns a random integer
between 0 and 9 .
( int )(Math.random() * 10 )
Returns a random integer
between 50 and 99 .
50 + ( int )(Math.random() * 50 )
In general,
Returns a random number between a
and a + b , excluding a + b .
a + Math.random() * b
 
 
Search WWH ::




Custom Search