Page 112 - Open Soource Technologies 304.indd
P. 112
Event Driven Programming
2 ^ 4 ‘result is 16
In the next article, we will try to see the hierarchy of mathematical operations.
5.2.5 Handling Operators And Operator Precedence
You have done well in your computer class, so well that the instructor has asked you to calculate
the average grade on the final. Nothing could be easier, you think, so you put together the
following program:
Private = Sub Command1_C1ick()
Dim intGrade1, IntGrade2, IntGrade3, NuberStrdents As Integer
intFrade1 = 60
intGrade2 = 70
IntGrade3 = 80
NumberStudent = 3
MsgBox (“Average grade = “&_
Str (IntGrade1 + IntGrade2 + IntGrade3/ NumberStudents))
End Sub
When you run the program, however, it calmly informs you that the average
score is 156.66666667.
That doesn’t look so good, what is wrong?
The problem lies in this line:
Str(intGrade1 + intGrade2 + intGrade3 / NumberStudents))
Visual Basic evaluates the expression in parentheses from left to right, using pairs of operands
and their associated operator, so it adds the first two grades together first. Instead of adding the
final grade, however, it first divides that grade by
NumberStudents, because the division operation has higher precedence than addition.
So the result is 60 + 70 + (80/3) = 156.66666667.
The solution here is to group the values to add together this way using parentheses:
Private Sub Command1_Click()
Dim intGrade1, intGrade2, intGrade3, NumberStudents As Integer
intGrade1 = 60
intGrade2 = 70
intGrade3 = 80
NumberStudents = 3
MsgBox (“Average grade = “ &_
Str((intGrade1 + intGrade2 + intGrade3)/ NumberStudents))
End Sub
Running this new code gives us an average of 70, as it should be.
106 LOVELY PROFESSIONAL UNIVERSITY