1 / 42

Chapter 3.3

Chapter 3.3. Numeric Data Types and Variables. Objectives. Create variables to store information while a solution runs Perform computations with variables using assignment statements Understand the role of precedence, perform type conversions, and format data

eagan
Télécharger la présentation

Chapter 3.3

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 3.3 Numeric Data Types and Variables

  2. Objectives • Create variables to store information while a solution runs • Perform computations with variables using assignment statements • Understand the role of precedence, perform type conversions, and format data • Write a statement on multiple lines and calculate solution output

  3. Storing Data in Variables • Variable stores data while a solution runs • A variable is simply a unique name that identifies a space in memory (RAM) • Data may be a string of characters or a number • Every variable has a data type • A variable's data type determines the kind of information that the variable can store • Numbers, characters, etc. • Every variable has a name • Use standard prefixes for variable names to denote data type

  4. Variables • A variable is a name that is used to refer to an item of data. The value assigned to the variable may change. • Up to 16,838 characters long • Begin with a letter or an underscore • Consist of only letters,digits and underscores • A Variable name is written in lowercase letters except for the first letters of additional words, such as costOfIT201.

  5. Numeric VB .NET Data Types

  6. Numeric VB .NET Data Types

  7. Standards for Variable Names • Use a one-character prefix to denote scope • The scope of a variable indicates which event handlers can use that variable • Module-level variables carry a prefix of "m“ • Global or Public variable carry a prefix of “g” • Use a three-character prefix to denote data type

  8. Standards for Variable Names

  9. Declaring a Variable • Private statement declares variable PrivatevarnameAstype [ = initialization expression] • varname is variable name • Astypecontains data type of variable • Optionalinitialization expressioncontains the initial value of a variable Example: Declare variables having the Double and Integer data types Private mdblInterestRate As Double Private mintCounter As Integer

  10. Declaring a Variable • Initialize a variable when declaring it • New to VB .NET Example: Declare a modular Integer variable and store the value 30 in the variable Private mintYearTerm As Integer = 30 Focus (m) Prefix (int) Name YearTerm

  11. Declaring a Variable • Do not include punctuation characters in a variable initialization • The following declarations are illegal because of the $ sign and commas: Private mdblInitialValue As Double = 100,000.52 Private mdblInitialValue As Double = $100,000.52 • Possible to declare multiple variables on the same line Private mintYearTerm, mintMonthTerm As Integer

  12. Declaring Module-Level Variables Declare module-level variables after the statements generated by the Window Form Designer but outside an event handler

  13. DIM Statement • DIM statement declares variable DIMvarnameAstype [ = initialization expression] • varname is variable name • Astypecontains data type of variable • Optionalinitialization expressioncontains the initial value of a variable Example: Declare variables having the Double and Integer data types DIM mdblInterestRate As Double DIM mintCounter As Integer

  14. Variable Initialization • Numeric variables are automatically initialized to 0: Dim varName As Double • To specify a nonzero initial value Dim varName As Double = 50

  15. Multiple Declarations • multiple-declaration statements : Dim a, b As Double Dim a As Double, b As Integer Dim c As Double = 2, b As Integer = 5

  16. Arithmetic Operators • Expressions consists of literal values, constants, variables and arithmetic operators • An arithmetic operator performs a mathematical calculation • Multiply the literal values 3 and 2 together and store the result (6) in the variable mintResult mintResult = 3 * 2 This is also called an assignment statement

  17. Arithmetic Operators (2)

  18. Arithmetic Operators – Example • Divide two numbers and multiply the intermediate result by 100 Private mdblNumerator As Double = 10 Private mdblDenominator As Double = 5 Private mdblResult As Double mdblResult = mdblNumerator / mdblDenominator * 100

  19. Arithmetic Operations • Numbers are called numeric literals • Five arithmetic operations in VB.NET + addition 3 + 2 - subtraction 3 - 2 * multiplication 3 * 2 / division 3 / 2 ^ exponentiation 3 ^ 2

  20. The Role of Precedence • Programming languages evaluate arithmetic expressions from left to right in a predefined order known as precedence • Perform exponentiation first • Next perform multiplication and division • Next perform Integer division and then apply the Mod operator • Next perform addition and subtraction • Parenthesis override default precedence • Parenthesis may be nested

  21. Precedence (Example) (Var1 + Var2) / (Var3 + Var4) * (Var5 ^ Var6) 1 (addition) 2 (addition) 3 (exponent) 4 (division) 5 (multiplication)

  22. Variables • Declaration: Dim dblSpeed As Double Data type Variable name • Assignment: • dblSpeed = 50

  23. Increment variable value • To add 1 to the numeric variable var var = var + 1 • Or as a shortcut var +=1

  24. Built-in Functions • Functions associates with one or more values and returns a value(output) • Math.sqrt(n): Returns the square root of n. Math.Sqrt(9) is 3 • Int(n): Returns greatest integer less than or equal to n Int(9.7) is 9

  25. Built-in Functions • Math.Round(n, r): • number n rounded to r decimal places Math.Round(2.317,1) is 2.3 Math.Round(2.7) is 3 • When n is halfway between two successive whole number, then it rounds to the nearest even number Math.Round(2.5) is 2 Math.Round(3.5) is 4

  26. Three Types of Errors • Syntax error – grammatical errors misspellings, omissions, incorrect punctuation • Run-time error occurs when program is running • Logic error program doesn’t perform as it is intended

  27. Type Conversion • VB .NET must convert data from one data type to another when evaluating mathematical expressions • TheOption Strict On statement enables strict type checking • Strict type checking requires explicit type conversion from less restrictive types to more restrictive types • Use strict type checking to minimize hard to find errors resulting from implicit type conversion

  28. Strict Type Checking (Example) • The following statement will cause an error if strict type checking is enabled. If disabled, mintPI will store the value 3 • Note that the result if the implicit type conversion is truncation Private mintPI As Integer = 3.14159

  29. Option Explicit • Option Explicit On statement requires that you declare variables before using them the first time • Also reduces hard to find errors resulting from typos • Note that Option Explicit and Option Strict statements appear at the beginning of a module

  30. Type Conversion Methods • Methods belong to the System.Convert class • ToInt16 converts value to a Short • ToInt32converts value to an Integer • ToInt64 converts value to a Long • ToDouble converts value to a Double • ToSingle converts value to a Single • ToString converts value to a String • Each method takes one argument; the value to convert • Note that these methods supercede older intrinsic functions like CInt and CLng

  31. Type Conversion Examples Private msngInput As Single = 3.44 Private mstrInput As String = "3.95“ ‘ why use “” Private mintOutput As Integer Private msngOutput As Single • Convert a Single to an Integer mintOutput = System.Convert.ToInt32(msngInput) • Convert a String to an Integer mintOutput = System.Convert.ToInt32(mstrInput) • Convert a String to a Single msngOutput = System.Convert.ToSingle(mstrInput)

  32. Numeric Overflow • Numericoverflow occurs when trying to store too large a number in a variable • The following statements will cause a numeric overflow error because the largest number that can be stored in a short is 32767 Private mshoExample As Short mshoExample = 46000 mshoExample = 2500 * 2500

  33. Numeric Overflow • VB .NET performs arithmetic using less restrictive type on right side of expression • The last statement will cause numeric overflow: Private mshoArg1 As Short, mshoArg2 As Short Private mintArg3 As Integer mshoArg1 = 32000 mshoArg2 = 32000 mintArg3 = mshoArg1 * mshoArg2

  34. Formatting a Numeric Value with Methods • The ToString type conversion method accepts a string argument to format data • Special characters are used to define the format lblGain.Text = mdblGain.ToString("$##,###.##") variable ToString method argument defines how to format the value

  35. Formatting Placeholders

  36. Formatting Examples

  37. Creating Well-Written Comments • A Comment is a full or partial line of text ignored by VB .NET • Create comments to describe what your code is doing or how code performs a particular task • Multiple comments are called a comment block • Blank lines between statements are ignored and are called whitespace • A comment can appear on its own line and begins with a single quote ( ' ) • A comment can appear at the end of a line

  38. Creating Well-Written Comments • The following is a comment appearing on its own line: ' This line is a comment. • The following comment appears at the end of a line. Note a space must precede the comment character txtDemo.text = "Dog" 'Store "Dog" in the text box Comment

  39. Creating Well-Written Comments VB .NET displays comments in in green

  40. Writing Assignment Statements Using Variables • Store a property in a variable mintResult = txtExample.Height • Store a literal value in a variable mintResult = 3 • Store another variable in a variable mintResult = mintExample

  41. Continuation Lines • Use when statement will not fit on a line • Underscore (_) is the continuation character • Rules for use • A Space (⇑) must precede the continuation character • You cannot follow a continuation character with a Comment • Do not break up words • Multiple continuation lines allowed

  42. Continuation Lines (Example) • The following statement appears on two lines: mdblInterestRate =⇑_ System.Convert.ToDouble(txtInterestRate.Text) / 100

More Related