Visual Basic Math

Computers are good with numbers, so it’s obvious they can perform mathematical calculations such as adding, subtracting, and square root, as well as cos, sin, tan, and hyp. At times, problems need to be solved, for example 2 + 6 * 5. You might think the answer to this is 40 ( 2 + 6 = 8 * 5 = 40 ), but in fact it is 32 (multiplication or division are always done first). You can force 2 + 6 to be calculated first by putting brackets around it like this:

Console.WriteLine((2 + 6) * 5)
Console.ReadLine()

Now the answer you should get is 40.

Another example is when there is multiplication and division; which one is done first? You start from the left to the right, for example:

Console.WriteLine(30 / 2 * 3)
        Console.ReadLine()

The answer for this is 45. Since we had both division and multiplication it starts from the left. Again, you can force 2 * 3 to be done first by putting brackets around it, and then the answer would be 5.

Division

With division you can format the result, for example:

 Dim Divide As Integer


        Divide = 5

        Console.WriteLine(9 / Divide)
        Console.ReadLine()

It will output 1.8. We can force this to an integer value by using CType function. Then it would look like this:

  Dim Divide As Integer


        Divide = 5

        Console.WriteLine(CType(9 / Divide, Integer))
        Console.ReadLine()

This time we use the CType function, and at the end specify the data type (integer). The result is 2, as it is converted to the nearest whole number.

Shorthand Math

You can use a much simpler way to do arithmetic:

Dim Shorthand As Integer

        Shorthand = 5

        Shorthand += 8


        Console.WriteLine(Shorthand)
        Console.ReadLine()

In this case we assign the variable Shorthand the value 5 then add 8, but just move the operator to the left of the equal sign. This works for addition, subtraction, and multiplication but not division, since the result can be a decimal value.

Other Math Functions

You can also find square roots, power and round. To do this, at the top above Module Module1 put Imports System.Math. Then write the following:

 Console.WriteLine(Sqrt(8))
        Console.ReadLine()

This finds the square root of 8, which is 2.828…….

Finding the power of 10 and 5:

Console.WriteLine(Pow(10, 5))
        Console.ReadLine()

The answer is 100,000.

Rounding:

  Console.WriteLine(Round(8.7))
        Console.ReadLine()

This rounds to 9 (do not confuse this with Rnd, which is Random).

There are many more math functions that can be done with the .Net Framework. For more information see the MSDN reference.

Summary

  • Multiplication and division are always done first
  • If there are both multiplication and division, start from left to right
  • For shorthand math put the operator on the left of the = sign
  • To use math functions such as sqrt, pow, round, make sure you import system.math