Microsoft® Windows® 2000 Scripting Guide
« Previous | Next »
Most of the calculations you carry out as a system administrator are likely to be simple ones, such as dividing bytes by 1,024 to convert the value to kilobytes. On occasion, however, you might need to carry out a calculation that involves more than one operator (for example, a calculation that adds two numbers and then divides that value). Because of that, it is important to understand arithmetic precedence.
VBScript does not treat the arithmetic operators (addition, subtraction, multiplication, and division) equally. Instead, when given an equation, VBScript always performs the math operations in this order:
Why does that matter to you? Consider the following script, which adds two numbers, multiplies them by a third, subtracts a fourth, and then divides by a fifth:
Wscript.Echo 1 + 2 * 3 - 4 / 5
When this script runs, the value 6.2 is echoed to the screen. Here is how that value is derived.
1 + 2 * 3 - .8
1 + 6 - .8
7 - .8
Of course, this might not be the answer, or the equation, you expected. Instead, you might have preferred that VBScript:
For this to happen, you need to use parentheses to indicate the preferred order of precedence. Parentheses always take precedence, regardless of the arithmetic operator being used. Because of this, your equation should be rewritten to ensure that the steps are carried out in the proper order. (When multiple parentheses are used, the equation within the innermost parentheses is evaluated first and the equation in the outermost parentheses evaluated last.)
Wscript.Echo (((1 + 2) * 3) - 4) / 5
Send us your feedback | « Previous | Next » |