4.4. Working with NumbersWe can manipulate numbers by combining them with operators to form mathematical expressions, and by calling built-in functions to perform complex mathematical operations. 4.4.1. Using OperatorsBasic arithmetic -- addition, subtraction, multiplication, and division -- is accomplished using the +, -, *, and / operators. Operators can be used with any numeric literals or data containers such as variables. Mathematical expressions are evaluated in the order determined by the precedence of the operators as shown in Table 5-1. For example, multiplication is performed before addition. All of these are legitimate uses of mathematical operators: x = 3 * 5; // Assign the value 15 to x x = 1 + 2 - 3 / 4; // Assign the value 2.25 to x x = 56; y = 4 * 6 + x; // Assign the value 80 to y y = x + (x * x) / x; // Assign the value 112 to y 4.4.2. Built-in Mathematical FunctionsTo perform advanced math, we use the built-in mathematical functions of the Math object. For example: Math.abs(x) // Absolute value of x Math.min(x, y) // The smaller of the values x and y Math.pow(x, y) // x raised to the power y Math.round(x) // x rounded to the nearest integer The math functions return values that we use in expressions, just as we use real numbers. For example, suppose we want to simulate a six-sided die. We can use the random( ) function to retrieve a random float between and 1: dieRoll = Math.random( ); Then we multiply that value by 6, giving us a float between and 5.999, to which we add 1: dieRoll = dieRoll * 6 + 1; // Sets dieRoll to a number between 1 and 6.999 Finally, we use the floor( ) function to round our number down to the closest integer: dieRoll = Math.floor(dieRoll); // Sets dieRoll to a number // between 1 and 6 Compressed into a single expression, our die roll calculation looks like this: // Sets dieRoll to a number between 1 and 6 dieRoll = Math.floor(Math.random( ) * 6 + 1); Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|