You are on page 1of 15

Visual Basic Mathematics

Variables and Math

Immediate-Command Window

Enables you to type mathematic al calculations to solve.
Print 20 + 50 + 10 80

Variables as Integer or Single

Integer
• Represents whole numbers between -32,768 and 32,767. • Ex. 240, -128, 2, etc.

Single
• Represents floating-point value – numerical value that has a decimal portion. • Ex. 12.75, 235.7584 Dim price as Single

Dim quantity as Integer

Long Integer
• •

A number that doesn’t fit into the integer range Range of –2,147,483,648 to 2,147,483,647.

Floating-Point Numbers

Single-Precision
• Accurate down to six decimal places

Double-Precision
• Accurate down to 14 decimal places

Ex. 34.875637

Ex.

657.364971122357 638

More Data Types

Variant
• Can contain almost any type of data – default data type • Leaves VB to figure out how to store the data. • Use up more memory, slowing down the program, ex:
Dim value1 Dim value2 As Variant

Currency
• Floating-Point type of number • Range of – 92233720368547 7.5808 to 92233720368547 7

Mixing Data Types
• •

totalValue = quantity * price Price is floating-point number, while quantity is integer. Data type will be to the left of the equals sign. totalValue is a Single type, so the result of the multiplication will be a singleprecision floating-point number

Equals sign (=)
• •

Doesn’t always mean equals Actually means “takes the value of”
• Example:

totalNumTapes = totalNumTapes + quantity

Arithmetic Operators
Operator
+ * / \ ^ MOD

Name
Addition Subtraction Multiplication Division Integer division Exponentiation Modulus

Use
Sum values Subtract values Multiply values Divide values Determine the whole number result of division Raise a value to a power Determine the remainder of division

Integer Division (\)

Using backslash character (\) will always give you an integer – drops the decimal point.
• Ex. 12\5 results in 2, rather than 2.4

Mod operator
• •

Also performs division, only gives remainder of the division Ex. 4 goes into 14 three times with a remainder of 2, so the operation 14 Mod 4 yields a result of 2. Won’t be used a lot

Exponentiation Operator (*)

Used to raise numbers to a power – multiplies the number times itself based on the exponent. Ex. 10^2 is the same as 10 * 10, which equals 100.

Order of Operations
1. 2. 3. • •

Exponentiation (^) Multiplication (*), Division (/), Integer Division (\) and Modulus (Mod) Addition (+) and Subtraction (-) Important for accurate calculations Operations of same precedence are evaluated from left to right.

Ex. 3 * 5 / 2 = 7.5

Order of Precedence

Can be changed by using parentheses
• •

Ex. totalValue = totalValue + price * quantity To: totalValue = (totalValue + price) * quantity

Any operation enclosed in parentheses is performed first.

Have a good day!!