Numeric Functions

Objectives


Discussion

Math Functions

Using Math Functions

Other Numeric Functions

Back to top


Demonstration

In this demo we will explore some math functions. 

1.  Create a new project - Unit6.  Add a button (btnMathFunctions) to the form.  Go to the click event for the button in the code window.

2.  Type "math." somewhere in the sub.  You should get a list of the math functions.  Now delete "math."  Type the following in the click event:

Dim a, b As Double
Dim c As Int16
a = Math.Round(6.89)
b = round(6.37)
c = Int(6.37)
MessageBox.Show(a & " " & b & " " & c)

3.  Notice that "round" in the third line is underlined. This is because it is not recognized since the round function is in the Math Namespace.  If you want to use these math functions you must use the word "Math" in front of the function or you can import the namespace.  At the very top of the code window (before the class definition) type:

Imports System.Math

4. Now "round" should no longer be underlined.  Now run your program and check out the results.  Now you know what round and int do. 

5.  You should experiment with the other math functions similarly to understand what they do.  Most important you should remember that they exist so that if you ever need one, you will know where to go for them.

6.  Now let's generate some random numbers.  VB.Net actually has a random data type that you could use.  But we are going to use the rnd() function.  Go into the code window somewhere and type "rnd", then click "F1".  You should be taken to Help on rnd.  If not then search for rnd in Help.  Once you have help on rnd, read it. Read the discussion of the example carefully.  Notice that it tells how to create a random number in a range.  Notice also that you should call Randomize before calling rnd. 

7.  Add another button (btnRandom).  Add a label (lblRandom) to your form.  Add the following code to the click event for the button to generate a number between 1 and 10:

Randomize()
Dim MyValue As Integer
MyValue = CInt(Int((10 * Rnd()) + 1))
lblRandom.Text = MyValue

8.  Run your program and test out the randomize feature.

Back to top
Exercises

1.  Create a form with one button.  When the user moves the mouse over the button, the button should move to a random location somewhere on the form.

2.  Write a program that simulates rolling dice.  When the user clicks a button, the computer should generate two numbers between 1 and 6 and display the dice accordingly.

3.  Recall that a quadratic equation has a form ax2 + bx + c = 0 where a, b, and c are numbers.  The goal is determine the value(s) of x that solve the equation.  The quadratic equation can be used to solve for x:

x = (-b + SQRT(b2 - 4ac))/(2a)

Write a program that prompts the user for a, b, and c and then determines the value(s) of x.

4.  Write code using the Random data type to generate a random number between 1 and 10.

Back to top
Links & Help
Back to top