Tuesday, February 8, 2011

Visual Basic 6.0 - Session 4

Create a calculator that can add, subtract, multiply and divide two numbers given by the user. A possible solution might use two input boxes (txtOne and txtTwo) and a label to display the answer (lblAnswer).

Declare  variables:
      dblNo1 As Double
      dblNo2 As Double
      dblAnswer As Double
      intError As Integer


Use Val function to change string from input box to a number, then an assignment statement to put that value into the variable.  
  
dblNo1=Val(txtOne.text)

Repeat for second number.

Use a Format function to ensure answer is rounded off to two decimal places.

lblAnswer.Caption=Format(dblAnswer,“#,##0.00”)

If you are very clever, this might be an option for the user.
Ensure that it is not possible to divide by zero, either by entering nothing or by entering zero.  Use the MsgBox() function to indicate the problem to the user.

If Val(txtTwo.Text)=0 Then
   IntError=MsgBox(“Youcannotdivideby0!”,VbOkCancel,“Whoops!)
Else…
 
EndIf

Add a clear command button with the following code to allow the user to do another calculation.

txtOne.Text=“”
txtTwo.Text=“”
lblAnswer.Caption=“”
txtOne.SetFocus

The SetFocus method returns the cursor to the first input box.

Set properties to pretty it up.
Check that it works.  Use integers, very big numbers, very small numbers, negative numbers, zeros, etc.  Is your label big enough for all values?  If you set the label’s autosize property to true it will stretch to fit.

Add a remark (put ‘ at the beginning of the line) at the top of your code which includes your name and the date. Connect to a Binary Selection menu heading on the main form.

Sequence algorithms
The programs in Activities 1 — 3 were all constructed from sequence algorithm constructs.  Each line of code followed another with only one possible pathway for each event.  So, for each sub procedure, the algorithm would consist of input, output and a series of process steps, e.g.  

Private Sub cmdClear_Click() `userinput
    xtOne.Text=“”                   `sequenceofprocessesinitializingvariables
    txtTwo.Text=“”
    lblAnswer.Caption=“”
    txtOne.SetFocus
EndSub `output

Binary selection 
The next group of programs you will write uses the second algorithm construct selection.  Selection allows multiple pathways for any event and allows for choices to be made.  Selection constructs can be Binary (two way) or Multiway (multiple choices)

Binary selection uses the If–EndIf or the If–Else–EndIf statements.  Here is the syntax in Visual Basic.

If comparison test Then
  One or more Visual Basic statements
End If
 
OR

If comparison test Then
  One or more Visual Basic statements
Else
  One or more Visual Basic Statements
End If

(You have used binary selection in your calculator to prevent a user dividing by zero.)

No comments:

Post a Comment