19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

5.10 The Math Class 199<br />

Math.sqrt(4) returns 2.0<br />

Math.sqrt(10.5) returns 3.24<br />

5.10.3 The Rounding Methods<br />

The Math class contains five rounding methods:<br />

/** x is rounded up <strong>to</strong> its nearest integer. This integer is<br />

* returned as a double value. */<br />

public static double ceil(double x)<br />

/** x is rounded down <strong>to</strong> its nearest integer. This integer is<br />

* returned as a double value. */<br />

public static double floor(double x)<br />

/** x is rounded <strong>to</strong> its nearest integer. If x is equally close<br />

* <strong>to</strong> two integers, the even one is returned as a double. */<br />

public static double rint(double x)<br />

/** Return (int)Math.floor(x + 0.5). */<br />

public static int round(float x)<br />

/** Return (long)Math.floor(x + 0.5). */<br />

public static long round(double x)<br />

For example,<br />

Math.ceil(2.1) returns 3.0<br />

Math.ceil(2.0) returns 2.0<br />

Math.ceil(-2.0) returns -2.0<br />

Math.ceil(-2.1) returns -2.0<br />

Math.floor(2.1) returns 2.0<br />

Math.floor(2.0) returns 2.0<br />

Math.floor(-2.0) returns -2.0<br />

Math.floor(-2.1) returns -3.0<br />

Math.rint(2.1) returns 2.0<br />

Math.rint(-2.0) returns -2.0<br />

Math.rint(-2.1) returns -2.0<br />

Math.rint(2.5) returns 2.0<br />

Math.rint(3.5) returns 4.0<br />

Math.rint(-2.5) returns -2.0<br />

Math.round(2.6f) returns 3 // Returns int<br />

Math.round(2.0) returns 2 // Returns long<br />

Math.round(-2.0f) returns -2 // Returns int<br />

Math.round(-2.6) returns -3 // Returns long<br />

Math.round(-2.4) returns -2 // Returns long<br />

5.10.4 The min, max, and abs Methods<br />

The min and max methods are overloaded <strong>to</strong> return the minimum and maximum numbers of<br />

two numbers (int, long, float, or double). For example, max(3.4, 5.0) returns 5.0,<br />

and min(3, 2) returns 2.<br />

The abs method is overloaded <strong>to</strong> return the absolute value of the number (int, long,<br />

float, or double). For example,<br />

Math.max(2, 3) returns 3<br />

Math.max(2.5, 3) returns 3.0<br />

Math.min(2.5, 3.6) returns 2.5

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!