Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

258 Part II Programming Fundamentals


statement that places the final calculation of the function in FunctionName. For example, the
Function procedure TotalTax computes the state and city taxes for an item and then assigns
the result to the TotalTax name, as shown here:

Function TotalTax(ByVal Cost as Single) As Single
Dim StateTax, CityTax As Single
StateTax = Cost * 0.05 'State tax is 5%
CityTax = Cost * 0.015 'City tax is 1.5%
TotalTax = StateTax + CityTax
End Function

Alternatively, you can return a value to the calling procedure by using the Return statement,
as shown in the following function declaration:

Function TotalTax(ByVal Cost as Single) As Single
Dim StateTax, CityTax As Single
StateTax = Cost * 0.05 'State tax is 5%
CityTax = Cost * 0.015 'City tax is 1.5%
Return StateTax + CityTax
End Function

I’ll use the Return syntax most often in this book, but you can use either mechanism for re-
turning data from a function.

Calling a Function Procedure


To call the TotalTax function in an event procedure, you use a statement similar to the
following:

lblTaxes.Text = TotalTax(500)

This statement computes the total taxes required for a $500 item and then assigns the result
to the Text property of the lblTaxes object. The TotalTax function can also take a variable as
an argument, as shown in the following statements:

Dim TotalCost, SalesPrice As Single
SalesPrice = 500
TotalCost = SalesPrice + TotalTax(SalesPrice)

The last statement uses the TotalTax function to determine the taxes for the number in the
SalesPrice variable and then adds the computed tax to SalesPrice to get the total cost of an
item. See how much clearer the code is when a function is used?

Using a Function to Perform a Calculation


In the following exercise, you’ll add a function to the Track Wins program to calculate the win
rate in the game—in other words, the percentage of spins in which one or more 7s appear.
To perform the calculation, you’ll add a function named HitRate and a public variable named
Free download pdf