Home and Learn: VB Net Course
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 asterisk symbol, above the number 8 on your keyboard, is used to multiply
/ 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 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 it's doing maths. 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? 12! It's wrong! But why?
You would think it would work out the sum like we do - left to right
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
To make sure Visual Basic does your sums correctly you have to be careful of the parentheses. Try changing the code to this:
answer = (8 - 4) + (4 + 2) * 2
Now what happens. That's right - you get 16! It's still wrong! At least it is if you are working from left to right. But Visual Basic isn't. It will do the (4 + 2) * 2 part first, and then add that to 8 - 4. Which gives you 16.
In order to force Visual Basic to get the sum right, you need even more parentheses. Try this code and see what happens:
answer= ((8 - 4) + (4 + 2)) * 2
Finally we get the answer we've been expecting - 20! The parentheses above have grouped our sums into separate sections, thereby forcing VB to do the sums in the right order.
So take care when using parentheses to do your sums: the order that Visual Basic does its sums does matter!
In the next section of the course, we'll have some fun adding menus to a Visual basic .NET form.
Buy the Book of this Course
Email us: enquiry at homeandlearn.co.uk