Visual Basic 6 Tutorial
By Junaid Shabbir
Views: 115981

Tips and trick of visual basic 6.
Math Functions (Page 10 of 14)

Math (Module)

The commonly used functions of Math module are
  • Math.abs
  • Math.round
  • Math.rnd
  • Math.randomize
  • Math.sin
  • Math.cos
  • Math.tan

The abs function returns an absolute(positive) value like

Dim x as Integer,a as integer,b as integer


x=Math.abs(-5) ' x contains 5
x=Math.abs(a-b) ' x contains 10

The round function can be used to round a number to the given decimal places like

Dim a as double,b as double

b=10/3 'b contains 3.33333333
a=Math.round(b,2) 'a contains 3.33
a=Math.round(5.678,2) 'a contains 5.68
a=Math.round(5.674,2) 'a contains 5.67

The rnd function returns a random number between 0 and 1. Generally the return value of rnd is multiplied with a number to get a specific range, like

Dim x as integer
x= round(rnd()*50,0) 'x will contain a number between 0 and 50

If the above two lines are placed in the ClickEvent of a CommandButton, you will receive a different number every time you click the button. But when you stop and again start your project, you will get the same sequence of numbers again, for example

Running the project first time gives the following numbers
23, 39, 12, 7, 44, 19

you will receive the same sequence of numbers each time you run your project. We can avoid this , and get a new sequence every time by using the randomize function.

The randomize function initializes the random number generator. Each time we use the randomize function, a new sequence of random numbers will be generated by the rnd function

Math.cos, Math.sin, Math.tan
Math.sin, Math.cos & Math.tan functions can be used to get trigonometric values of sine, cosine and tangent. These functions are mostly used in graphics related programs. These functions have only on paramter i-e the angel (in radians)

The following code demonstrates the use of cos & sin functions
Place a CommonButton on your form and name it cmdDrawCircle, place the following code in the button’s click event

Private sub cmdDrawCircle_Click()

Dim r As Integer, i as integer
Dim x As Integer, y As Integer
Dim cx As Integer, cy As Integer
r = 2000
cx = 2000: cy = 2000
For i = 0 To 359

x = r * Cos(toRadian(CDbl(i)))
y = r * Sin(toRadian(CDbl(i)))
Me.PSet (cx + x, cx + y), RGB(255, 0, 0)

Next i

End Sub

Private Function toRadian(d As Double) As Double

toRadian = (3.14 / 180) * d

End Function


r is the radius of circle
cx,cy is the center of circle

The Pset function gives color to a single pixel The toRadians function converts the angle from degree into radians