2. The Visual Basic Language
Exercise 2-1: Computing a Mean and Standard Deviation
- Develop an application that allows the user to input a sequence of
numbers. When done inputting the numbers, the program should compute
the mean of that sequence and the standard deviation. If N numbers are
input, with the ith number represented by xi, the formula for the
mean ( ) is:
and to compute the standard deviation (s), take the square root of
this equation:
s2 = [ N - ( )2 ] /
[ N ( N - 1 ) ]
The Greek sigmas in the above equations simply indicate that you add
up all the corresponding elements next to the sigma.
My Solution:
Form:
Properties:
Form frmStats:
Caption = Mean and Standard Deviation
CommandButton cmdExit:
CommandButton cmdAccept:
CommandButton cmdCompute:
CommandButton cmdNew:
TextBox txtInput:
FontName = MS Sans Serif
FontSize = 12
Label lblStdDev:
Alignment = 2 - Center
BackColor = &H00FFFFFF& (White)
BorderStyle = 1 - Fixed Single
FontName = MS Sans Serif
FontSize = 12
Label Label6:
Caption = Standard Deviation
Label lblMean:
Alignment = 2 - Center
BackColor = &H00FFFFFF& (White)
BorderStyle = 1 - Fixed Single
FontName = MS Sans Serif
FontSize = 12
Label Label4:
Label lblNumber:
Alignment = 2 - Center
BackColor = &H00FFFFFF& (White)
BorderStyle = 1 - Fixed Single
FontName = MS Sans Serif
FontSize = 12
Label Label2:
Label Label1:
Caption = Number of Values
Code:
General Declarations:
Option Explicit
Dim NumValues As Integer
Dim SumX As Single
Dim SumX2 As Single
Const vbKeyMinus = 45
Const vbKeyDecPt = 46
cmdAccept Click Event:
Private Sub cmdAccept_Click()
Dim Value As Single
txtInput.SetFocus
NumValues = NumValues + 1
lblNumber.Caption = Str(NumValues)
�Get number and sum number and number-squared
Value = Val(txtInput.Text)
SumX = SumX + Value
SumX2 = SumX2 + Value ^ 2
txtInput.Text = ""
End Sub
cmdCompute Click Event:
Private Sub cmdCompute_Click()
Dim Mean As Single
Dim StdDev As Single
txtInput.SetFocus
�Make sure there are at least two values
If NumValues < 2 Then
End If
�Compute mean
Mean = SumX / NumValues
lblMean.Caption = Str(Mean)
�Compute standard deviation
StdDev = Sqr((NumValues * SumX2 - SumX ^ 2) /
(NumValues * (NumValues - 1)))
lblStdDev.Caption = Str(StdDev)
End Sub
cmdExit Click Event:
Private Sub cmdExit_Click()
End Sub
cmdNew Click Event:
Private Sub cmdNew_Click()
'Initialize all variables
txtInput.SetFocus
NumValues = 0
lblNumber.Caption = "0"
txtInput.Text = ""
lblMean.Caption = ""
lblStdDev.Caption = ""
SumX = 0
SumX2 = 0
End Sub
txtInput KeyPress Event:
Private Sub txtInput_KeyPress(KeyAscii As Integer)
'Only allow numbers, minus sign, decimal point, backspace,
return keys
If (KeyAscii >= vbKey0 And KeyAscii <= vbKey9)
Or KeyAscii = vbKeyMinus Or KeyAscii = vbKeyDecPt
Or KeyAscii = vbKeyBack Then
ElseIf KeyAscii = vbKeyReturn Then
Else
End If
End Sub
Counter Hit
This Homepage is special brought to you by CK Tan