1 / 51

第 6 章 – 程序

第 6 章 – 程序.

ambersmiley
Download Presentation

第 6 章 – 程序

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. 第 6章 – 程序 大綱6.1 介紹6.2   一般模組(Modules),類別( Classes) and 程序(Procedures)6.3   Sub程序(Procedures)6.4   Function程序(Procedures)6.5   方法(Methods)6.6   Option 的宣告(Strict) 和 資料型態的轉換6.7 值型態及參照型態  6.8   傳遞參數: Pass-by-Value vs. Pass-by-Reference6.9 遞迴6.10   遞迴例子:費氏數列The Fibonacci Series6.11   遞迴與重複

  2. 大綱6.12 多載程序和選項參數(Procedure Overloading and Optional Arguments6.13   一般模組 (Modules)

  3. (6-1)介 紹 • 程序為程式的基本單位 • Vb.net 程序分為 sub ,function, property,event 四種 # 物件導向程式中 sub, 及 function為方法 property 為屬性

  4. 6.2 模組類別及程序 • Framework 類別函式庫 • 提供豐富的類別及方法去執行操作 • 數學操作 • 字串操作 • 字元操作 • 輸入輸出操作 • 錯誤檢查

  5. 介紹

  6. 6.2模組類別及程序 • 程式設計者自訂的程序 • Foundation class(fcl)無法提供所有程式使用 • 四種程序 • Sub程序 • Function程序 • Property程序 • Event程序 • 程序觸發是由程序呼叫

  7. 6.2模組類別及程序 經理 員工1 員工2 員工3 員工4 員工5 Fig. 6.1 模組階層關析

  8. 6.2模組類別及程序 • 軟體以程序為基本單位 • 為何把程式劃分為程序 • 將程式分為程序易於在程式發展中管理 • 程式易於重複使用 • 避免重複使用的程式碼

  9. 6.2模組類別及程序 • 早期的的程式只有一個稱為fcl方法的程序 • 隨後 程式中包含自訂的程序

  10. PrintPay形式引數hours and wage 接收所有實際引數 Main程序呼叫printpay程序 所有的程序必須在模組或類別中定義( PrintPay在modPayment. ) 1 ' Fig. 6.2: Payment.vb 2 ' Sub procedure that prints payment information. 3 4 Module modPayment 5 6 Sub Main() 7 8 ' call Sub procedure PrintPay 4 times 9 PrintPay(40, 10.5) 10 PrintPay(38, 21.75) 11 PrintPay(20, 13) 12 PrintPay(50, 14) 13 14 Console.ReadLine() ' prevent window from closing 15 End Sub' Main 16 17 ' print amount of money earned in command window 18 Sub PrintPay(ByVal hours AsDouble, ByVal wage AsDecimal) 19 20 ' pay = hours * wage 21 Console.WriteLine("The payment is {0:C}", hours * wage) 22 EndSub' PrintPay 23 24 EndModule' modPayment Payment.vbProgram Output The payment is $420.00 The payment is $826.50 The payment is $260.00 The payment is $700.00

  11. 6.3 Sub 程序 • 程序定義的格式 Sub程序名稱(參數列) 宣告及敘述 EndSub • 程序標頭 • sub • 程序名稱 緊跟sub 關鍵字 • 為一識別字 • 程式的sub 程序 • 程序主體 • 宣告及敘述

  12. 6.4 Function程序 • 與sub 類似 • 與sub差異 • Function 呼叫會傳回一個值(代表函數)sub不傳回值

  13. The For structure displays the results of squaring the Integers from 1-10 Square(i) 呼叫square Return 敘述傳回一個值且終結程式的執行 1 ' Fig. 6.3: SquareInteger.vb 2 ' Function procedure to square a number. 3 4 ModulemodSquareInteger 5 6 Sub Main() 7 Dim i As Integer ' counter 8 9 Console.WriteLine("Number" & vbTab & "Square" & vbCrLf) 10 11 ' square numbers from 1 to 10 12 For i = 1To10 13 Console.WriteLine(i & vbTab & Square(i)) 14 Next 15 16 End Sub ' Main 17 18 ' Function Square is executed 19 ' only when the function is explicitly called. 20 Function Square(ByVal y As Integer) As Integer 21 Return y ^ 2 22 End Function' Square 23 24 End Module' modSquareInteger SquareInteger.vb

  14. Number Square 1 1 2 4 3 9 4 16 5 25 6 36 7 49 8 64 9 81 10 100 SquareInteger.vb輸出

  15. 6.4 Function程序 程序定義的格式Function程式名稱(參數列) As傳回值的資料型態 宣告及敘述 EndFunction 傳回值的資料型態 • 傳回值的資料型態 • Return expression - 可在function內任一位置 • 傳回一個值 • 跳回程序呼叫點

  16. 6.5 方法 • Definition of method • A 在類別中的程序含sub 及function • FCL 方法 • 自訂類別中的方法

  17. 所有表單均繼承 System.Windows.Forms.Form類別 事件捕捉 cmdMaximum_Click (捕捉)Handles按鈕(cmdMaximum)的clicked事件 宣告在圖形介面中所使用的控制項在工具箱中產生可見元件 1 ' Fig. 6.4: Maximum.vb 2 ' Program finds the maximum of three numbers input. 3 4 PublicClass FrmMaximum 5 Inherits System.Windows.Forms.Form 6 7 ' prompts for three inputs 8 FriendWithEvents lblOne As System.Windows.Forms.Label 9 FriendWithEvents lblTwo As System.Windows.Forms.Label 10 FriendWithEvents lblThree As System.Windows.Forms.Label 11 12 ' displays result 13 FriendWithEvents lblMaximum As System.Windows.Forms.Label 14 15 ' read three numbers 16 FriendWithEvents txtFirst As System.Windows.Forms.TextBox 17 FriendWithEvents txtSecond As System.Windows.Forms.TextBox 18 FriendWithEvents txtThird As System.Windows.Forms.TextBox 19 20 ' reads inputs and calculate results 21 Friend WithEvents cmdMaximum As System.Windows.Forms.Button 22 23 ' Visual Studio .NET generated code 24 25 ' obtain values in each text box, call procedure Maximum 26 PrivateSub cmdMaximum_Click(ByVal sender As System.Object, _ 27 ByVal e As System.EventArgs) Handles cmdMaximum.Click 28 Maximum.vb

  18. 從文書盒的text屬性取的值 呼叫fcl的函數必須參照類別名稱及點運算子(.) 以程序名稱呼叫方法 29 Dim value1, value2, value3 AsDouble 30 31 value1 = txtFirst.Text 32 value2 = txtSecond.Text 33 value3 = txtThird.Text 34 35 lblMaximum.Text = Maximum(value1, value2, value3) 36 EndSub ' cmdMaximum_Click 37 38 ' find maximum of three parameter values 39 Function Maximum(ByVal valueOne AsDouble, _ 40 ByVal valueTwo AsDouble, ByVal valueThree AsDouble) 41 42 Return Math.Max(Math.Max(valueOne, valueTwo), valueThree) 43 EndFunction ' Maximum 44 45 EndClass ' FrmMaximum Maximum.vb輸出

  19. 6.5 方法 參數資訊視窗 Fig. 6.5Visual Studio .NET IDE 的.參數資訊視窗

  20. 6.5方法 Fig. 6.6 IntelliSense Visual Studio .NET IDE. 的IntelliSense

  21. 6.5 方法 (method) Fig. 6.7 Math class methods.

  22. 6.5方法 Fig. 6.7 Math class methods.

  23. 6.6 Option Strict and Data-Type 轉換 • Option Explicit • On 為預設值 • 強迫所有的變數使用前必須宣告 • Option strict • Off 為預設值 • 若為on則強迫變數必須宣告變數資料型態 • Class Convert • 類別轉換的方法明確轉換資料型態

  24. 6.7值資料型態及參照型態 Fig. 6.9 Property Pages dialog with Option Strict set to On.

  25. 6.7值資料型態及參照型態 • 帶有值得變數資料型態 • 包含實際值得變數 • 使用於單一值 • 整數 • 被精確浮點數 • 參照變數 • 包含一個記憶體所在的位置 • 已知的物件 • 尾隨字(訂資料型態) • 在程式中直接訂值得資料型態 • 為相對應一原形資料型態

  26. 6.7 值資料型態及參照型態 Fig. 6.10 Visual Basic primitive data types.

  27. 6.7值型態及參照轉換 Fig. 6.11 尾隨字.

  28. 6.8 傳遞參數: Pass-by-Value vs. Pass-by-Reference • (傳值呼叫)Pass-by-value • 程式呼叫程序時會複製一實際引數值並傳給被呼叫程序 • (傳參照呼叫) Pass-by-reference • 呼叫敘述呼叫被呼叫程序時傳遞參照讓被呼叫程序能存取及修正呼叫敘述的原始資料 *visual basic.net (沒有傳址呼叫)

  29. 實際引數number1被傳遞, 其值被複製一份傳給squarebyvalue程序 number2的參照被傳遞 1 ' Fig. 6.12: ByRefTest.vb 2 ' Demonstrates passing by reference. 3 4 Module modByRefTest 5 6 ' squares three values ByVal and ByRef, displays results 7 Sub Main() 8 Dim number1 As Integer = 2 9 10 Console.WriteLine("Passing a value-type argument by value:") 11 Console.WriteLine("Before calling SquareByValue, " & _ 12 "number1 is {0}", number1) 13 SquareByValue(number1) ' passes number1 by value 14 Console.WriteLine("After returning from SquareByValue, " & _ 15 "number1 is {0}" & vbCrLf, number1) 16 17 Dim number2 AsInteger = 2 18 19 Console.WriteLine("Passing a value-type argument"& _ 20 " by reference:") 21 Console.WriteLine("Before calling SquareByReference, " & _ 22 "number2 is {0}", number2) 23 SquareByReference(number2) ' passes number2 by reference 24 Console.WriteLine("After returning from " & _ 25 "SquareByReference, number2 is {0}" & vbCrLf, number2) 26 27 Dim number3 As Integer = 2 28 ByRefTest.vb

  30. ByVal指出以傳值傳遞 強制運算子強制傳值方式 ByRef指出以傳參照傳遞 29 Console.WriteLine("Passing a value-type argument" & _ 30 " by reference, but in parentheses:") 31 Console.WriteLine("Before calling SquareByReference " & _ 32 "using parentheses, number3 is {0}", number3) 33 SquareByReference((number3)) ' passes number3 by value 34 Console.WriteLine("After returning from " & _ 35 "SquareByReference, number3 is {0}", number3) 36 37 End Sub ' Main 38 39 ' squares number by value (note ByVal keyword) 40 Sub SquareByValue(ByVal number As Integer) 41 Console.WriteLine("After entering SquareByValue, " & _ 42 "number is {0}", number) 43 number *= number 44 Console.WriteLine("Before exiting SquareByValue, " & _ 45 "number is {0}", number) 46 End Sub' SquareByValue 47 48 ' squares number by reference (note ByRef keyword) 49 Sub SquareByReference(ByRef number As Integer) 50 Console.WriteLine("After entering SquareByReference" & _ 51 ", number is {0}", number) 52 number *= number 53 Console.WriteLine("Before exiting SquareByReference" & _ 54 ", number is {0}", number) 55 End Sub' SquareByReference 56 57 End Module' modByRefTest ByRefTest.vb

  31. Passing a value-type argument by value: Before calling SquareByValue, number1 is 2 After entering SquareByValue, number is 2 Before exiting SquareByValue, number is 4 After returning from SquareByValue, number1 is 2 Passing a value-type argument by reference: Before calling SquareByReference, number2 is 2 After entering SquareByReference, number is 2 Before exiting SquareByReference, number is 4 After returning from SquareByReference, number2 is 4 Passing a value-type argument by reference, but in parentheses: Before calling SquareByReference using parentheses, number3 is 2 After entering SquareByReference, number is 2 Before exiting SquareByReference, number is 4 After returning from SquareByReference, number3 is 2 輸出

  32. Automatic variable value is destroyed when MethodA terminates 1 ' Fig. 6.13: Scoping.vb 2 ' Demonstrates scope rules and instance variables. 3 4 Public Class FrmScoping 5 Inherits System.Windows.Forms.Form 6 7 Friend WithEvents lblOutput As System.Windows.Forms.Label 8 9 ' Windows Form Designer generated code 10 11 ' instance variable can be used anywhere in class 12 Dim value AsInteger = 1 13 14 ' demonstrates class scope and block scope 15 PrivateSub FrmScoping_Load(ByVal sender As System.Object, _ 16 ByVal e As System.EventArgs) HandlesMyBase.Load 17 18 ' variable local to FrmScoping_Load hides instance variable 19 Dim value AsInteger = 5 20 21 lblOutput.Text = "local variable value in" & _ 22 " FrmScoping_Load is " & value 23 24 MethodA() ' MethodA has automatic local value 25 MethodB() ' MethodB uses instance variable value 26 MethodA() ' MethodA creates new automatic local value 27 MethodB() ' instance variable value retains its value 28 29 lblOutput.Text &= vbCrLf & vbCrLf & "local variable " & _ 30 "value in CScoping_Load is " & value 31 EndSub' FrmScoping_Load 32 33 ' automatic local variable value hides instance variable 34 Sub MethodA() 35 Dim value As Integer = 25' initialized after each call Scoping.vb

  33. 變數 值為(line 12的外部變數) . 36 37 lblOutput.Text &= vbCrLf & vbCrLf & "local variable " & _ 38 "value in MethodA is " & value & " after entering MethodA" 39 value += 1 40 lblOutput.Text &= vbCrLf & "local variable " & _ 41 "value in MethodA is " & value & " before exiting MethodA" 42 EndSub' MethodA 43 44 ' uses instance variable value 45 Sub MethodB() 46 lblOutput.Text &= vbCrLf & vbCrLf & "instance variable" & _ 47 " value is " & value & " after entering MethodB" 48 value *= 10 49 lblOutput.Text &= vbCrLf & "instance variable " & _ 50 "value is " & value & " before exiting MethodB" 51 EndSub' MethodB 52 53 End Class ' FrmScoping Scoping.vb

  34. 6.9 遞迴 • 遞迴程序(ecursive procedure ) • 遞迴可直接或間接遞迴 • 解決事情的一種演算法 • 遞迴程序可看出演算法中解決事情的最容易的例子 • 對於複雜的問題可利用遞迴由簡化程序 • 遞迴呼叫 • 自我呼叫程序

  35. 6.9 遞迴(階層) 5! 5! Final value = 120 5 * 4! 5 * 4! 5! = 5 * 24 = 120 is returned 4 * 3! 4 * 3! 4! = 4 * 6 = 24 is returned 3 * 2! 3 * 2! 3! = 3 * 2 = 6 is returned 2 * 1! 2 * 1! 2! = 2 * 1 = 2 is returned 1 1 1 returned (a) 遞迴呼叫程序 (b) 每一遞迴的傳回值 Fig. 6.18 遞迴呼叫5!.

  36. 轉換字串成整數 1 ' Fig. 6.19: Factorial.vb 2 ' Calculating factorials using recursion. 3 4 PublicClass FrmFactorial 5 Inherits System.Windows.Forms.Form 6 7 FriendWithEvents lblEnter As Label ' prompts for Integer 8 FriendWithEvents lblFactorial As Label ' indicates output 9 10 FriendWithEvents txtInput As TextBox ' reads an Integer 11 FriendWithEvents txtDisplay As TextBox ' displays output 12 13 FriendWithEvents cmdCalculate As Button ' generates output 14 15 ' Visual Studio .NET generated code 16 17 PrivateSub cmdCalculate_Click(ByVal sender As System.Object, _ 18 ByVal e As System.EventArgs) Handles cmdCalculate.Click 19 20 Dim value AsInteger = Convert.ToInt32(txtInput.Text) 21 Dim i AsInteger 22 Dim output AsString 23 24 txtDisplay.Text = "" 25 26 For i = 0To value 27 txtDisplay.Text &= i & "! = " & Factorial(i) & vbCrLf 28 Next 29 30 EndSub ' cmdCalculate_Click Factorial.vb

  37. If number大於 1則執行遞迴呼叫 若沒有結束條件傳回值則會發生錯誤 31 32 ' recursively generates factorial of number 33 Function Factorial(ByVal number AsLong) AsLong 34 35 If number <= 1Then' base case 36 Return1 37 Else 38 Return number * Factorial(number - 1) 39 EndIf 40 41 EndFunction ' Factorial 42 43 EndClass ' FrmFactorial Factorial.vb

  38. 6.10 遞迴:費氏數列( Fibonacci Series) • 費氏數列 • 前二項為0 ,1 fib(0)=0,fib(1)=1 • 其他項為其前二項之和 fib(n)=fib(n-1)+fib(n-2) • 黃金比例 • 費氏數列會收斂成黃金比例1.618 • 費氏數列 • 每一項為為其前二項之和 • 如第30項為 2,692,537

  39. 非遞迴 遞迴呼叫 1 ' Fig. 6.20: Fibonacci.vb 2 ' Demonstrating Fibonacci sequence recursively. 3 4 PublicClass FrmFibonacci 5 Inherits System.Windows.Forms.Form 6 7 Friend WithEvents lblPrompt As Label ' prompts for input 8 Friend WithEvents lblResult As Label ' displays result 9 10 Friend WithEvents cmdCalculate As Button ' calculates result 11 12 Friend WithEvents txtInputBox As TextBox ' reads an Integer 13 14 ' Visual Studio .NET generated code 15 16 ' displays Fibonacci number in txtInputBox 17 PrivateSub cmdCalculate_Click(ByVal sender As System.Object, _ 18 ByVal e As System.EventArgs) Handles cmdCalculate.Click 19 20 ' read input 21 Dim number AsInteger = Convert.ToInt32(txtInputBox.Text) 22 23 lblResult.Text = "Fibonacci Value is " & Fibonacci(number) 24 EndSub ' cmdCalculate_Click 25 26 ' calculate Fibonacci value recusively 27 Function Fibonacci(ByVal number AsInteger) As Long 28 29 ' check for base cases 30 If number = 1OrElse number = 0Then 31 Return number 32 Else 33 Return Fibonacci(number - 1) + Fibonacci(number - 2) 34 EndIf 35 Fibonacci.vb

  40. 36 EndFunction ' Fibonacci 37 38 End Class ' FrmFibonacci Fibonacci.vb

  41. Fibonacci( 3 ) return Fibonacci( 2 ) Fibonacci( 1 ) return Fibonacci( 1 ) Fibonacci( 0 ) return 1 return 0 return 1 6.11費氏數列的遞迴呼叫 Fig. 6.21 費氏數列的遞迴呼叫

  42. 6.11 遞迴與重複 • 重複(Iteration) • 重複結構 • For, While or Do/LoopUntil • 遞迴 • 遞迴程序呼叫 • 使用選擇結構 • If/Then, If/Then/Else or Select • 遞迴呼叫浪費執行時間(程序呼叫控制權轉移)及記憶體

  43. 6.12 程序過載(overloading)及選項參數 • 過載(Overloading) • 同名的程序但參數的個數或資料型態不依樣 • 可增加程式的可讀式 • 選項參數(Optional arguments) • 呼叫程序時才決定傳遞的參數

  44. 1 ' Fig. 6.22: Overload.vb 2 ' Using overloaded methods. 3 4 PublicClass FrmOverload 5 Inherits System.Windows.Forms.Form 6 7 Friend WithEvents outputLabel As Label 8 9 ' Visual Studio .NET generated code 10 11 PrivateSub FrmOverload_Load(ByVal sender As System.Object, _ 12 ByVal e As System.EventArgs) Handles MyBase.Load 13 14 outputLabel.Text = "The square of Integer 7 is " & _ 15 square(7) & vbCrLf & "The square of Double " & _ 16 "7.5 is " & square(7.5) 17 EndSub ' FrmOverload_Load 18 19 Function Square(ByVal value AsInteger) AsInteger 20 Return Convert.ToInt32(value ^ 2) 21 End Function ' Square 22 23 Function Square(ByVal value AsDouble) AsDouble 24 Return value ^ 2 25 End Function ' Square 26 27 End Class ' FrmOverload Overload.vb

  45. 1 ' Fig. 6.23: Overload2.vb 2 ' Using overloaded procedures with identical signatures and 3 ' different return types. 4 5 PublicClass FrmOverload2 6 Inherits System.Windows.Forms.Form 7 8 Friend WithEvents outputLabel As Label 9 10 ' Visual Studio .NET generated code 11 12 PrivateSub FrmOverload2_Load(ByVal sender As System.Object, _ 13 ByVal e As System.EventArgs) Handles MyBase.Load 14 15 outputLabel.Text = "The square of Integer 7 is " & _ 16 square(7) & vbCrLf & "The square of Double " & _ 17 "7.5 is " & square(7.5) 18 EndSub ' FrmOverload2_Load 19 20 Function Square(ByVal value AsDouble) AsInteger 21 Return Convert.ToInt32(value ^ 2) 22 End Function ' Square 23 24 Function Square(ByVal value AsDouble) AsDouble 25 Return value ^ 2 26 End Function ' Square 27 28 End Class ' FrmOverload2 Overload2.vb

  46. The creating of overloaded procedures with identical parameter lists and different return types produces a syntax error Overload2.vbProgram Output

  47. 6.13一般模組Modules • 一般模組Modules • 相關程序行程群組以利重複引用 • 與類別引用類似

  48. 1 ' Fig. 6.25: DiceModule.vb 2 ' A collection of common dice procedures. 3 4 Imports System.IO 5 6 Module modDice 7 8 Dim randomObject As Random = New Random() 9 10 ' rolls single die 11 Function RollDie() AsInteger 12 Return randomObject.Next(1, 7) 13 EndFunction ' RollDie 14 15 ' die summation procedure 16 Function RollAndSum(ByVal diceNumber AsInteger) _ 17 AsInteger 18 19 Dim i As Integer 20 Dim sum AsInteger = 0 21 22 For i = 1To diceNumber 23 sum += RollDie() 24 Next 25 26 Return sum 27 EndFunction ' RollAndSum DiceModule.vb

  49. 28 29 ' returns die image 30 Function GetDieImage(ByVal dieValue AsInteger, _ 31 OptionalByVal baseImageName AsString = "die") _ 32 As System.Drawing.Image 33 34 Return Image.FromFile( _ 35 Directory.GetCurrentDirectory & _ 36 "\Images\" & baseImageName & dieValue & ".png") 37 EndFunction ' GetDieImage 38 39 EndModule' modDice DiceModule.vb

  50. 1 ' Fig. 6.26: DiceModuleTest.vb 2 ' Demonstrates modDiceModule procedures 3 4 Imports System.Drawing 5 6 PublicClass FrmDiceModuleTest 7 Inherits System.Windows.Forms.Form 8 9 FriendWithEvents lblSum As Label ' displays 10-roll sum 10 11 FriendWithEvents diceGroup As GroupBox 12 13 ' dice images 14 FriendWithEvents picDie1 As PictureBox 15 FriendWithEvents picDie2 As PictureBox 16 17 FriendWithEvents cmdRollDie1 As Button ' rolls blue die 18 FriendWithEvents cmdRollTen As Button ' simulates 10 rolls 19 FriendWithEvents cmdRollDie2 As Button ' rolls red die 20 21 ' Visual Studio .NET generated code 22 23 PrivateSub cmdRollDie1_Click(ByVal sender As System.Object, _ 24 ByVal e As System.EventArgs) Handles cmdRollDie1.Click 25 26 picDie1.Image = modDice.GetDieImage(modDice.RollDie()) 27 EndSub ' cmdRollDie1_Click 28 29 PrivateSub cmdRollDie2_Click(ByVal sender As System.Object, _ 30 ByVal e As System.EventArgs) Handles cmdRollDie2.Click 31 32 picDie2.Image = modDice.GetDieImage(modDice.RollDie(), _ 33 "redDie") 34 EndSub ' cmdRollDie2_Click 35 DiceModuleTest.vb

More Related