Game Development Reference
In-Depth Information
The Multiplication and Division Operators
These operators are also fairly self-explanatory; the multiplication operator multiplies numbers
together and the division operator divides the number on the left by the number on the right:
int number1 = 4;
int number2 = 2;
int multiplied = number1 * number2;
int divided = number1 / number2;
The result of the multiplication would be 8 and the result of the division would be 2.
The division operator, like the subtraction operator, has a result that depends on the order of the
variables.
int divided1 = number1 / number2;
int divided2 = number2 / number1;
After executing these lines of code, divided1 would store 2 as earlier but divided2 would store 0 as
4 cannot divide into 2. You can think of the results of the division as being rounded down to the
nearest whole integer. The following example shows a similar result.
int number1 = 5;
int number2 = 2;
int divided1 = number1 / number2;
int divided2 = number2 / number1;
In the preceding code, divided1 will contain 2 after execution. The actual math would be 5/2 = 2.5
or 2 remainder 1, but as integers can only store whole numbers we lose the extra 0.5 or remainder.
2/5 = 0 remainder 5, and again we lose the remainder; therefore divided2 will store 0.
float divided2 = static_cast<float>(number2) / static_cast<float>(number1);
Casting both numerator and denominator to float values (or dividing two float variables) would have
yielded a result of 0.5f. This is why it is important to use the correct type of variable for the job at hand.
The Modulo Operator
Our guessing game in Listing 2-1 has already shown a usage of the modulo operator. This can be
thought of as a remainder operator, as it will return the remainder of dividing one number by another.
int numerator = 12;
int denominator = 10;
int remainder = numerator % denominator;
The variable remainder shown here will store the value 2 as 12 divided by 10 equals 1 remainder 2.
 
Search WWH ::




Custom Search