Lunes, Agosto 1, 2011

Basic Calculator Tutorial in Visual Basic

Today, we will be making a basic calculator with Visual Basic. Start by creating a new project, select “Windows Form Application” and name it “BasicCalculator” and then click “OK”.
Start by adding 2 text boxes, 2 labels and 4 buttons to the form.
image
Next, neaten up the form by giving appropriate names and text to the items:
image
Here I have made the form look neat and given appropriate names to each object.
Now, let’s add the code!
Double click on “btnTimes” and add this code:
Dim num1 As Double = txtNum1.Text
Dim num2 As Double = txtNum2.Text
lblAnswer.Text = num1 * num2
This code takes the values from txtNum1 and txtNum2, multiply them and then output the answer as the text for lblAnswer. As you can see, we have used the “Double” type over the “Integer” data type so that the user can use a range of numbers and still get the correct output.
Double click on “btnDivide” and add this code:
Dim num1 As Double = txtNum1.Text
Dim num2 As Double = txtNum2.Text
lblAnswer.Text = num1 / num2
As you can see, this is similar code to the code that was applied to “btnTimes”. All that has changed is the operator. This will divide the two numbers instead of multiplying them.
Do the same for the other two buttons (“btnAdd” and “btnMinus”) and let’s test the program!
btnTimes:
image
Here we have entered the values 5 and 2 and clicked on “btnTimes”. As we can see, it has output the correct answer of 10. (5 x 2 = 10)
btnDivide:
image
Here we have entered the values 5 and 2 and clicked on “btnDivide”. As we can see, it has output the correct answer of 10. (5 / 2 = 2.5)
btnAdd:
image
Here we have entered the values 5 and 2 and clicked on “btnAdd”. As we can see, it has output the correct answer of 10. (5 + 2 = 7)
btnMinus:
image
Here we have entered the values 5 and 2 and clicked on “btnMinus”. As we can see, it has output the correct answer of 10. (5 - 2 = 3)


Walang komento:

Mag-post ng isang Komento