Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^110) | Arithmetic Expressions


8 % 8 0

8 % 9 8

8 % 7 1

0 % 7 0

5.0 % 2.3 0.4

Be careful with division and modulus calculations. For instance, the expressions 7 / 0 and
7 % 0 will produce error messages, because the computer cannot divide an integer by zero.
With floating-point values, however, the expressions 7.0/ 0.0and 7.0% 0.0do not result
in error messages. The result of the expression 7.0 / 0.0is a special value representing in-
finity. The result of 7.0 % 0.0is another special value called not a number(NaN).
Calculations involving these special values produce unusual results. For example, the re-
sult of any arithmetic operation involving NaN is also NaN. If you encounter such results, they
indicate that you need to carefully reexamine the expressions in your code to confirm that
division and remainder cannot have a zero divisor.
Because variables are allowed in expressions, the following are valid assignments:

alpha = num + 6;
alpha = num / 2;
num = alpha * 2;
num = 6 % alpha;
alpha = alpha + 1;
num = num + alpha;

As we saw with assignment statements involving Stringexpressions, the same variable
can appear on both sides of the assignment operator. In the case of

num = num + alpha;

the value in numand the value in alphaare added together, and then the sum of the two val-
ues is stored into num, replacing the value previously stored there. This example shows the
difference between mathematical equality and assignment. The mathematical equality

num= num+ alpha

is true only when alphaequals zero. The assignment statement

num = num + alpha;

is valid for anyvalue of alpha.
Here’s a simple application that uses arithmetic expressions:

T


E


A


M


F


L


Y


Team-Fly®

Free download pdf