In the preceding sections, all the operators mentioned yield results which have the same mode as the operand or operands. In this and following sections, we shall see that this is not always the case.
Division poses a problem because division by integers can have two
different meanings. For example, 3 ÷ 2
can be taken to mean 1
or 1.5
. In this
case, we use two different operator symbols.
Integer division is represented by the symbol
%
. It takes operands of mode INT
and yields
a value of mode INT
. It has the alternative
representation OVER.
The formula 7 % 3 yields the value 2
, and the
formula -7 % 3 yields the value -2
. The
priority of %
is 7, the same as
multiplication. Here are some identity declarations using the
operator:
INT r = 23 OVER 4, s = -33 % 3; INT q = r * s % 2
Using the given values of r
and s
, the value of
q
is -27
. When a formula containing
consecutive dyadic operators of the
same priority is elaborated, elaboration is always left-to-right, so
in this case the multiplication is elaborated first, followed by the
integer division. Of course, %
can be combined with
subtraction as well as all the other operators already discussed.
The modulo operator
MOD gives the remainder
after integer division. It requires two operands of mode
INT
and yields a value also of mode INT
.
Thus 5 MOD 3
yields 2
, and 12 MOD
3
yields 0
. It does work with negative integers,
but the results are unexpected. You can explore MOD
with
negative integers in an exercise. MOD
can also be
written as %*
. The priority of MOD
is 7.
Division of real numbers is performed by the
operator /. It takes two operands of mode
REAL
and yields a REAL
result. Thus the
formula 3.0/2.0
yields 1.5
. Again,
/
can be combined with *
and the other
operators already discussed. It has a priority of 7. The
operator is also defined for integer operands. Thus 3/2
yields the value 1.5
. No widening
takes place here since the operator is defined to yield a value of
mode REAL
when its operands have mode
INT
.
Here are some identity declarations using the operators described so far:
REAL pi by 2 = pi / 2, pm3 = pi - 3.0 * -4.1; INT c = 22 % 3 - 22 MOD 3; INT d = c MOD 6 + SIGN -36
5 * 4
5 % 4
5 / 4
5 MOD 4
5.0 * 3.5 - 2.0 / 4.0
MOD
with
negative integer operands. Try either operand negative, then both
operands negative. Anstwo pi
. AnsSian Mountbatten 2012-01-19