The Division Operators

The operators /, \, and Mod all involve division. However, one importa nt difference among the three division operators is how they report the results of the division.

Using as an example 11 divided by 4, the result is 2, remainder 3. The 2 is the quotient, the 3 the remainder. The results reported by the three division operators are:

■ The / operator reports the entire result, 2 remainder 3, expressed as a decimal, 2.75.

■ The \ operator reports only the quotient, 2, and drops the remainder. Integer division does not round off. If it did, 11 \ 4 would be 3, not 2.

■ The Mod operator reports only the remainder, 3, and drops the quotient.

Another important difference among the three division operators concerns the data types of their operands. The operands in floating point division may be either whole or floating point numbers. By contrast, the operands in integer division should be whole numbers.

Note The consequences of using a floating point operand in integer division depend on whether Option Strict is on. If an operand in integer division is a floating point number, it first must be coerced to a whole number before integer division can be performed. If Option Strict is on, such implied coercion is not permitted, and a compiler error results. If Option Strict is off, the implied coercion of the floating point number to a whole number is permitted. However, given the limitations of a whole number, one result of the conversion is that the part of the number to the right of the decimal point is lost. Thus, 3.93 \ 2.2 would be regarded as 3\ 2, with the result of 1.

The Mod operator, like floating point division, may have as operands either whole or floating point numbers. If both operands are whole numbers, the remainder necessarily will be a whole number. For example, 10 Mod 5 is 0, and 10 Mod 3 is 1. However, if either operand is a floating point number, the remainder may be a floating point number. For example, 12.5 Mod 5 is 2.5.

You often will use the / operator, which performs floating point division, as it provides you with the complete result. However, the Change Machine Project later in this module shows you that the \ and Mod operators can also be very useful.

Tip Programmers sometimes find it difficult to recall which of the / and \

operators is floating point division and which is integer division. One mnemonic is that the / is a forward slash, and the "f" in forward corresponds to the "f" in floating point. Another memory technique is that the / looks more like the normal arithmetic division operator than does the \, and floating point division produces the normal quotient and remainder result of arithmetic division, whereas integer division does not.

Was this article helpful?

0 0

Post a comment