Lecture: Types and Arithmetic

Download Report

Transcript Lecture: Types and Arithmetic

Practical Programming
COMP153-08S
Arithmetic and Types
Admin – room changes
COMP153-08S (HAM) TUT 01 for Tuesday 8 January only
Time: Tue 9:00 - 11:00
Location: I.G.02
COMP153-08S (HAM) LEC 01
Time: Mon 9:00 - 11:00
Location: K.G.07
COMP153-08S (HAM) TUT 01
Time: Tue 9:00 - 11:00;
Location: K.G.06
COMP153-08S (HAM) LEC 02
Time: Wed 9:00 - 11:00
Location: K.G.07
COMP153-08S (HAM) TUT 02
Time: Thu 9:00 - 11:00
Location: K.G.06
Arithmetic
• Note: Lecture notes (and labs) are
on the web at:
www.cs.waikato.ac.nz/~geoff
• Operations
– Add
– Multiply
– Subtract
– Divide
– Power
+
*
/
^
eg: 3^2 is 32
Order of operations
• Unless you use parentheses to say
otherwise
– Power is first
– Then multiplication and division done
in order from left to right
– Then addition and subtraction in order
from left to right
Examples
• 2+3*4
– Is 14, evaluated as 2 + (3 * 4)
– If you want the addition done first,
then you must write (2 + 3) * 4
• 30 / 2 * 3
– Is 45, done strictly from left to right
– If you want this to mean 30 / 6 then
you must write 30 / (2 * 3)
Types
• All values stored in a computer
have a ‘Type’ – ie: the VB system
has to know what kind of value it is
dealing with – so it knows what
operations can be performed on the
value and how much storage to
make available for it.
Examples of Types
• Integer
– Holds whole numbers, roughly in the
range +/- 2 billion
– Eg:
Button1.Width = 200
• String
– Hold sequences of characters – text
– Eg:
Button1.Text = “Press Me”
– VB makes no attempt to ‘understand’
the content of a string
Another Type
• Single and Double
– Hold fractional or very large numbers
– Eg:
2.34
–
1.5E6
means 1.5 * 106
–
2.03E-5 means 2.03 * 10-5
Operations on Types
• Integer values can have arithmetic
operations applied to them
• So can single and double values
• Interestingly there is an operation
that can be applied to String values
The + operator joins two strings
“ABC” + “DEF” gives “ABCDEF”
Type Conversion
• VB tries to be helpful and convert
values from one type to another, in
order to make sense of statements.
• TextBox1.Text = TextBox2.Text * 3.4
• Doesn’t make sense – we cannot
multiply a String by a number
• However VB will convert text to
number, multiply and convert back
Care
• Automatic conversion doesn’t
always do what we want
• We can explicitly do it ourselves
– Val(…) converts String to number
– Str(…) converts from number to String
• Eg:
• Eg:
Val(Text1.Text)
Str(100 * 34)
Copy program - before
Enter data into textbox and
click Copy
Results in:
Exercise
• Try the same design but change the
first box to Fahrenheit and the
second to Celsius
• Change the Copy button to Convert
• C = (F – 32)/1.8
THE END
of the lecture