Download presentation
Presentation is loading. Please wait.
Published byCynthia White Modified over 8 years ago
1
1 Computer Programming Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology andres@dlit.edu.tw http://www.cse.dlit.edu.tw/~andres
2
2 Chapter 4 Numeric Types and Expressions
3
3 Chapter 4 Topics Constants of Type Integer and Double lEvaluating Arithmetic Expressions lIncrement and Decrement Operators lImplicit Type Conversion and Explicit Type Casting lCalling a Value-Returning Method Using VB.NET Math class methods String Operations Length, IndexOf, Substring
4
4 4.1 VB.NET Primitive Data Types primitive Integral Boolean Byte Char Short Integer Long Single Double Floating Point
5
5 VB.NET Data Types Reference Array Interface Class primitive Integral Boolean Byte Char Short Integer Long Single Double Floating Point VB.NET Data Types
6
6 Primitive and Reference Types letter Dim letter As Char Dim title As String Dim bookName As String letter = "J" title = " Programming with VB.NET " bookName = title
7
7 Primitive and Reference Types letter title Dim letter As Char Dim title As String Dim bookName As String letter = "J" title = " Programming with VB.NET " bookName = title
8
8 Primitive and Reference Types letter title bookName Dim letter As Char Dim title As String Dim bookName As String letter = "J" title = " Programming with VB.NET " bookName = title
9
9 Primitive and Reference Types letter title bookName Dim letter As Char Dim title As String Dim bookName As String letter = "J" title = " Programming with VB.NET " bookName = title "J"
10
10 Primitive and Reference Types letter title bookName 2002 "Programming with VB.NET " Memory Location 2002 "J" Dim letter As Char Dim title As String Dim bookName As String letter = "J" title = " Programming with VB.NET " bookName = title
11
11 Dim letter As Char Dim title As String Dim book As String letter = "J" title = " Programming with VB.NET " book = title Primitive and Reference Types letter title bookName 2002 "Programming with VB.NET " Memory Location 2002 "J"
12
12 Primitive and Reference Types Dim letter As Char Dim title As String Dim book As String letter = "J" title = " Programming with VB.NET " bookName = title letter title bookName 2002 "Programming with VB.NET " Memory Location 2002 "J"
13
13 4.2Primitive Data Types in VB.NET Integral Types n can represent whole numbers and their negatives when declared as Short, Integer, or Long n can represent single characters when declared as Char Floating Point Types n represent real numbers with a decimal point n declared as Single, or Double
14
14 Samples of VB.NET Data Values Integer sample values 4578 -4578 0 Double sample values 95.274 95..265 Char sample values ‘ B ’ ‘ d ’ ‘ 4 ’ ‘ ? ’‘ * ’
15
15 Integral Types Type Size in Bits Minimum Value to Maximum Value Byte 8 -128 to 127 Short16 -32,768 to 32,767 Integer32 -2,147,483,648 to 2,147,483,647 Long64 -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807
16
16 Sizes of Integral VB.NET Types Byte 8 bits Short 16 bits Integer 32 bits Long 64 bits
17
17 Using one byte ( = 8 bits ), HOW MANY DIFFERENT NUMBERS CAN BE REPRESENTED USING 0’s and 1’s? Each bit can hold either a 0 or a 1. So there are just two choices for each bit, and there are 8 bits. 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 = 2 8 = 256 0 1 1 0 0 0 1 1
18
18 Similarly, using two bytes (= 16 bits), 2 16 = 65536 DIFFERENT NUMBERS CAN BE REPRESENTED. If we wish to have only one number representing the integer zero, and half of the remaining numbers positive, and half negative, we can obtain the 65,536 numbers in the range below : -32768.... 0.... 32767 0 1 0 0 1 0 1 0 0 1 1 0 0 0 1 1
19
19 Exponential (Scientific) Notation 2.7E4 means 2.7 x 10 4 = 2.7000 = 27000.0 2.7E-4 means 2.7 x 10 - 4 = 0002.7 = 0.00027
20
Type Size in Bits Range of Values Single32 +1.4E - 45 to +3.4028235E+38 Double64 +4.9E - 324 to +1.7976931348623157E+308 Floating Point Types
21
21 More About Floating Point Types lFloating-point types have an integer part and a fractional part, with a decimal point in between. Either the integer part or the fractional part, but not both, may be missing. EXAMPLES 18.4 500..8 -127.358 lAlternatively, floating point values can have an exponent, as in scientific notation. The number preceding the letter E doesn’t need to include a decimal point. EXAMPLES 1.84E1 5E2 8E-1 -.127358E3
22
22 4.3 Declarations for Numeric Types lNamed constant declaration Const PI As Double =3.14159 Const E As Single = 2.71828F Const MAX_TEMP As Long = 1000000000L Const MIN_TEMP As Integer = -273
23
23 Variable Declarations Dim student As Integer Dim sumOfScore As Integer Dim sumOfSquare As Long Dim average As Double Dim deviation As Simgle
24
24 4.4 What is an Arithmetic Expression? l An arithmetic expression is a valid arrangement of variables, constants, operators and parentheses. l An expression can be evaluated to compute a value of a given type. l The value of the expression 9.3 * 4.5 is 41.85
25
25 Some VB.NET Operators OperatorDescription ( )Parentheses +Positive - Negative *Multiplication / Division % Modulus (remainder) +Addition - Subtraction = Assignment
26
26 Operator lOperand, operator lUnary operator nAn operator that has just one operand. n+ (positive), -(negative) lBinary operator nAn operator that has two operand. n+ (Addition), - (Subtraction), *, /, %, =
27
27 Division Operator lThe result of the division operator depends on the type of its operands. lIf one or both operands has a floating type, the result is a floating point type (float or double). Otherwise, the result is an integral type. EXAMPLES 11 / 4 has value 2 11.0 / 4.0 has value 2.75 11 / 4.0 has value 2.75
28
28 Modulus Operator lThe modulus operator % when used with integer type operands has an integer type result. lIts result is the integer type remainder of an integer division. EXAMPLE 11 % 4 has value 3 because ) 4 11 2 and Remainder = ?
29
29 ' ************************************************* ' FreezeBoil program ' This program computes the midpoint between ' the freezing and boiling points of water ' ************************************************* Imports System.ComponentModel'Import component handling Imports System.Drawing'Import graphics Imports System.WinForms 'I mport forms, event ' handling types Public Class Form1 'Create form for output Inherits System.WinForms.Form Const FREEZE_PT As Double = 32 'Freezing pt of water Const BOIL_PT As Double = 212 'Boiling pt of water Dim avgTemp As Double 'Holds the result of 'averaging FREEZE_PT and 'BOIL_PT Public Sub New() MyBase.New() Form1 = Me
30
30 'This call is required by the Win Form Designer InitializeComponent() lblFreeze.Text = "Water freezes at " & FREEZE_PT lblFreeze.text = lblFreeze.Text & " and boils at “ & _ BOIL_PT & " degrees." avgTemp = FREEZE_PT + BOIL_PT avgTemp = avgTemp / 2 lblFreeze.Text = lblFreeze.Text & "Halfway between is"_ & avgTemp & "degrees."
31
31 4.5 Compound VB.NET Operators Precedence OperatorDescription Higher ( )Parentheses +Positive - Negative *Multiplication / Division % Modulus (remainder) +Addition - Subtraction Lower = Assignment
32
32 Precedence lHigher Precedence determines which operator is applied first in an expression having several operators.
33
33 Associativity lLeft to right Associativity means that in an expression having 2 operators with the same priority, the left operator is applied first. (left to right) lIn VB.NET, the binary operators *, /, %, +, - are all left associative. Expression 9 - 5 + 1 means ( 9 - 5 ) + 1 not 9 – (5 +1 ) 4 + 1 5
34
34 VB.NET Operator Precedence (highest to lowest) Operator Associativity. ( ) ( args ) Left to right unary: + - Right to left New ( type ) Right to left * / % Left to right + - Left to right = Right to left
35
35 7 * 10 - 5 % 3 * 4 + 9 means (7 * 10) - 5 % 3 * 4 + 9 70 - 5 % 3 * 4 + 9 70 - (5 % 3) * 4 + 9 70 - 2 * 4 + 9 70 - ( 2 * 4 ) + 9 70 - 8 + 9 ( 70 - 8 ) + 9 62 + 9 71 Evaluate the Expression
36
36 Parentheses lParentheses can be used to change the usual order. lParts in ( ) are evaluated first. Evaluate (7 * (10 - 5) % 3) * 4 + 9 ( 7 * 5 % 3 ) * 4 + 9 ( 35 % 3 ) * 4 + 9 2 * 4 + 9 8 + 9 17
37
37 More VB.NET Operators Dim age As Integer age = 8 age = age + 1 age 98
38
38 Variable = Expression First, Expression on right is evaluated. Then the resulting value is stored in the memory location of Variable on left. NOTE: An automatic type conversion occurs after evaluation but before the value is stored if the types differ for Expression and Variable Assignment Operator Syntax
39
39 What value is stored? Dim a As Double Dim b As Double a = 8.5 b = 9.37 a = b a b a b 8.5 9.37 ? ?
40
40 What value is stored? Dim a As Double Dim b As Double a = 8.5 b = 9.37 a = b a b a b 8.5 9.37
41
41 What is stored? ? Dim someDouble As Single someDouble = 12 ' implicit type conversion someDouble 12.0 someDouble
42
42 What is stored? ? Dim someInt As Integer someInt someInt = 4.8 ' implicit type conversion someInt 4
43
43 Implicit type conversion occurs... Whenever values of different data types are used in: 1. arithmetic expressions 2. assignment operations TWO RULES APPLY...
44
44 Type conversion lThe implicit (automatic) conversion of a value from one data type to another. lWidening conversion nA type conversion that dose not result in a loss of information. lnarrowing conversion nA type conversion that may result in a loss of some information, as in converting a value of type Double to Single.
45
45 A widening conversion... l Is a type conversion that does not result in a loss of information. Specifically, for mixed type expressions using both integer and floating-point type values: Step 1. The integer value is temporarily converted to a floating-point value. Step 2. The operation is performed. Step 3. The result is a floating-point value.
46
46 lIs a type conversion that may result in a loss of information. FOR EXAMPLE, 98.6 98 temperature number Dim temperature As Double = 98.6 Dim number As Integer number = temperature 'loss occurs A narrowing conversion...
47
47 CInt converts its argument to an Integer type. CLng converts its argument to a Long type. CSng converts its argument to a Single type. CDbl converts its argument to a Double type. Type Conversation is Explicit Conversion of Type
48
48 CInt(4.8) has value 4 CDbl(5) has value 5.0 CDbl(7/4) has value 1.0 CDbl(7) / CDbl(4) has value 1.75 Type Conversation is Explicit Conversion of Type
49
49 Some Expressions Dim age As Integer EXAMPLE someDouble = CDbl(3 * someInt + 2) someInt = CInt(5.2 / someDouble – 2.0) someSingle = someInt + 8 someSingle = CSng( someInt + 8 ) CDbl ( 4 / 8 )0.0 CDbl ( 4 ) / 80.5
50
50 What values are stored? Dim loCost As Double Dim hiCost As Double loCost = 12.342 hiCost = 12.348 loCost = CDbl (CInt (loCost * 100.0 + 0.5)) / 100.0 hiCost = CDbl (CInt (hiCost * 100.0 + 0.5)) / 100.0
51
51 Values Rounded to 2 Decimal Places 12.34 hiCost 12.35 loCost
52
52 4.6 Method Call lA method call temporarily transfers control to the called method’s code to perform a task. lWhen the method’s code has finished executing, control is transferred back to the calling block.
53
53 Where are VB.NET methods? located in class libraries OR written by programmers
54
54 Write a VB.NET expression... To find the larger of myAge and yourAge and place it in variable older Dim older As Integer
55
55 Write a VB.NET expression... To find the larger of myAge and yourAge and place it in variable older Dim older As Integer... older = Math.Max ( myAge, yourAge )
56
56 Write a VB.NET expression... To find the square root of b 2 - 4ac and place it in variable d. Dim a, b, c, d As Double
57
57 Write a VB.NET expression... To find the square root of b 2 - 4ac and place it in variable d. Dim a, b, c, d As Double... d = Math.Sqrt ( b * b - 4.0 * a * c )
58
58 Some Math class methods Math.Abs ( x ) Math.Abs( -9.8 ) is 9.8 ' absolute value of x Math.Sqrt( x ) Math.Sqrt( 9.0 ) is 3.0 ' square root of a non-negative x Math.Log ( x ) Math.Log( 1.0 ) is 0 ' natural (base e) logarithm of x Math.Max ( x, y ) Math.Max( 2.5, 6.7) is 6.7 ' larger value of x and y Math.Pow ( x, y ) Math.Pow( 9, 0.5 ) is 3.0 ' x raised to the power y
59
A method call uses the name of the method followed by ( ) enclosing a list of parameters. Console.WriteLine ("Done") older = Math.Max (myAge, your Age) number = Math.Sqrt (456.34) A method call temporarily transfers control to the called method to perform its task. Method Calls
60
Two Kinds of Methods Always is called as part of an expression. Does some task. Returns a value that takes its place in the expression. Always is called as a separate statement. Does some task. Never returns a value to its caller. Value-Returning Non-value Returning
61
61 ObjectName.MethodName( Parameter List ) The parameter list is used to communicate values to the method by passing information. The parameter list can contain 0, 1, or more parameters, separated by commas, depending on the method. Method Call Syntax
62
62 4.7 Additional String Operations Length method Method Length returns an Integer value that equals the number of characters in the string. You must use dot notation and parentheses in the call to method Length.
63
63 What value is returned? ' Using methods Length Dim firstName As String Dim fullName As String Dim len As Ineger firstName = " Alexandra “ len = firstName.Length( ) fullName = firstName & “Jones” len = fullName.Length( )
64
64 IndexOf method Method IndexOf searches a string to find a particular substring, and returns an Integer value that is the beginning position for the first occurrence of that substring within the string. The substring argument can be a literal String, a String expression, or a Char value. If the substring could not be not found, method IndexOf returns value -1.
65
65 What value is returned? ' Using methods IndexOf Dim phrase As String Dim position As Integer phrase = “The dog and the cat " position = phrase.IndexOf(“the” ) position = phrase.IndexOf(“rat” ) Dim theString As String theString = “Abracadaba " position = theString.IndexOf(“a”c )
66
66 What value is returned? ' Using methods IndexOf Dim str1 As String Dim str2 As String str1 = “Programming and Problem Solving " str2 = “gram" str1.IndexOf(“and” ) str1.IndexOf(“Programming” ) str2.IndexOf(“and” ) str1.IndexOf(“Pro” ) str1.IndexOf(“ro” & str2 ) str1.IndexOf(“pr” & str2 ) str1.IndexOf(“ ” )
67
67 Substring method Method Substring returns a particular substring of a string, but does not change the string itself. The first parameter is an Integer that specifies a starting position within the string. The second parameter is an Integer that is 1 more than the ending position of the substring. l Positions of characters within a string are numbered starting from 0, not from 1.
68
68 What value is returned? ' Using methods Length, IndexOf, Substring Dim myString As String = "Programming and Problem Solving " myString.Substring ( 0, 7) myString.Substring ( 7, 8) myString.Substring ( 11, 1) myString.Substring ( 24, 7) myString.Substring ( 24, 1)
69
69 What value is returned? ' Using methods Length, IndexOf, Substring Dim stateName As String = " Mississippi " stateName.Length( ) value 11 stateName.IndexOf ( " is ") value 1 stateName.Substring( 0, 4 ) value “Miss” stateName.Substring( 4, 6 )value “is” stateName.Substring( 9, 11 ) value “pi”
70
70 Map Measurement Case Study l You want a program to determine walking distances between 4 sights in the city. l Your city map legend says one inch on the map equals 1/4 mile in the city. l You use the measured distances between 4 sights on the map. l Display the walking distances (rounded to the nearest tenth) between each of the 4 sights.
71
71 '******************************************************* ' Walk program ' This program computes the mileage (rounded to nearest ' tenth of mile) for each of 4 distances, given the ' measurements on a map with scale of 1 in = 0.25 mile ' ******************************************************* Imports System.ComponentModel Imports System.Drawing Imports System.WinForms Public Class Form1 Inherits System.WinForms.Form VB.NET Case Study Program
72
72 VB.NET Case Study Continued Const DISTANCE1 As Double = 1.5 ‘Measurement for 1 st distance Const DISTANCE2 As Double = 2.3 'Measurement for 2 nd distance Const DISTANCE3 As Double = 5.9 'Measurement for 3 rd distance Const DISTANCE4 As Double = 4R 'Measurement for 4 th distance Const MAP_SCALE As Double = 0.25 'Map SCALE Dim totMiles As Double 'Total of rounded mileage Dim miles As Double 'An individual rounded mileage Public Sub New() My Base.New Form1 = Me InitializeComponent() totMiles = 0R
73
73 'Compute and display miles for each distance on the map 'Output will not display.0 amounts miles = CDbl(CInt(DISTANCE1 * MAP_SCALE * 10R + 0.5) / 10R) lblDistance1.Text = "For a measurement of " & DISTANCE1 & _ " the first distance is " & miles _ & " mile(s) long. " totMiles = totMiles + miles miles = CDbl(CInt(DISTANCE2 * MAP_SCALE * 10R + 0.5) / 10R) lblDistance2.Text = "For a measurement of " & DISTANCE2 & _ " the second distance is " & miles & _ " mile(s) long." totMiles = totMiles + miles miles = CDbl(CInt(DISTANCE3 * MAP_SCALE * 10R + 0.5) / 10R) lblDistance3.Text = "For a measurement of " & DISTANCE2 & _ " the second distance is " & miles & _ " mile(s) long."
74
74 totMiles = totMiles + miles miles = CDbl(CInt(DISTANCE4 * MAP_SCALE * 10R + 0.5) / 10R) lblDistance4.Text = "For a measurement of " & DISTANCE2 & _ " the second distance is " & miles & _ " mile(s) long." totMiles = totMiles + miles lblTotMiles.Text = "Total mileage for the day is " & _ totMiles & " miles." End Sub 'Form overrides dispose to clean up the component list. Overrides Public Sub Dispose() MyBase.Dispose components.Dispose End Sub #Region " Windows Form Designer generated code " #End Region End Class
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.