.Net Tuto Part 31 :The Basic Math Symbols in VB .NET

If you’re doing any programming, you need to know how to use the basic Math symbols. The basic Math symbols in Visual Basic .NET are these:

+ The Plus sign adds numbers together The minus sign takes one number away from another * The symbol above the number 8 on your keyboard tells Visual Basic to multiply two numbers / The forward slash on your keyboard is the divide by symbol = The equals sign

A word or two about how to use the mathematical symbols in Visual Basic. You can use the operators by themselves:

answer = 8 + 4
answer = 8 – 4
answer = 8 * 4
answer = 8 / 4

Or you can combine them by using round brackets (parentheses).

Here, Visual Basic will work out the sums in parentheses first, and then add the two sums together

answer = (8 – 4) + (4 -2)
answer = 4 + 2
answer = 6

But you’ve got to be careful with parentheses, because there is a strict order that VB uses when doing its Math. Consider this sum

answer = 8 – 4 + 4 + 2 * 2

Try that code behind a new button. Display the result in a MsgBox. What answer did you get? Was it the answer you were expecting?

If you didn’t pick up much Math in school, you might do the sum from left to right, thereby giving you an answer of 20.

8 – 4 = 4
+ 4 = 8
+ 2 = 10
* 2 = 20

But VB doesn’t work it out like that. Visual Basic will do the multiplying first. So it will calculate like this:

2 * 2 = 4
8 – 4 + 4 = 8
8 + 4 = 12

But try changing the code to this:

answer = (8 – 4) + (4 + 2) * 2

Here, we’ve added some parentheses.

Run the code and see what happens. That’s right – you get 16! This time, Visual Basic will do the (4 + 2) * 2 part first, and then add that to 8 – 4. Which gives you 16.

Try this code and see what happens:

answer= ((8 – 4) + (4 + 2)) * 2

Now we get an entirely different answer – 20! The parentheses above have grouped our sums into separate sections, and we now get a third solution to our seemingly simple calculation.

The lesson to learn here is to take care when mixing different Math symbols. Use parentheses to spell out to VB exactly what you mean.

 

In the next section of the course, we’ll have some fun adding menus to a Visual basic .NET form.

Leave a comment