Java Reference
In-Depth Information
Here is a typical use for the integer / and % operations. Suppose you want to know
how much change a cash register should give, using separate values for dollars and
cents. You can compute the value as an integer, denominated in cents, and then
compute the whole dollar amount and the remaining change:
final int PENNIES_PER_NICKEL = 5;
final int PENNIES_PER_DIME = 10;
final int PENNIES_PER_QUARTER = 25;
final int PENNIES_PER_DOLLAR = 100;
// Compute total value in pennies
int total = dollars * PENNIES_PER_DOLLAR + quarters
* PENNIES_PER_QUARTER
+ nickels * PENNIES_PER_NICKEL + dimes *
PENNIES_PER_DIME + pennies;
// Use integer division to convert to dollars, cents
int dollars = total / PENNIES_PER_DOLLAR;
int cents = total % PENNIES_PER_DOLLAR;
For example, if total is 243, then dollars is set to 2 and cents to 43.
To compute x n , you write Math.pow(x, n) . However, to compute x 2 it is
significantly more efficient simply to compute x * x .
The Math class contains methods sqrt and pow to compute square roots and
powers.
To take the square root of a number, you use the Math.sqrt method. For example,
is written as Math.sqrt(x) .
x
In algebra, you use fractions, superscripts for exponents, and radical signs for roots to
arrange expressions in a compact two-dimensional form. In Java, you have to write
all expressions in a linear arrangement. For example, the subexpression
b 2
2 a
ɨ b +
ɨ 4ac
of the quadratic formula becomes
(-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a)
149
Search WWH ::




Custom Search