跳轉到內容

程式設計基礎:內建函式

來自華夏公益教科書,開放世界開放書籍

試卷 1 - ⇑ 程式設計基礎 ⇑

← 異常處理 內建函式 隨機數生成 →


你需要熟悉大多數常見程式語言中內建的幾個程式設計例程。這些例程非常有用,可以節省你在編寫程式碼以執行常見任務方面的大量工作。你可能會被要求在考試中使用它們,所以要學習它們!

算術函式

[編輯 | 編輯原始碼]

你必須熟悉幾個

舍入函式用於使用 Math.Round() 函式將數字舍入到有限的小數位數

Math.Round(1.94, 1) 'Returns 1.9
Math.Round(1.95, 1) 'Returns 1.9 !0.5 rounds down!
Math.Round(1.96, 1) 'Returns 2.0
Math.Round(1.9445, 2) 'Returns 1.94
Math.Round(1.9545, 3) 'Returns 1.954
Math.Round(6.765, 2) 'Returns 6.76
Math.Round(1.9445) 'Returns 2 - the equivalent of saying round to 0 dp

截斷函式返回數字的整數部分,而不管小數位數。

Math.Truncate(19.45) 'Returns 19
Math.Truncate(19.9999) 'Returns 19

這在嘗試在 模算術 中執行 DIV 時特別有用。

擴充套件:隨機數

大多數遊戲的一個重要部分是使用隨機數的能力。這些可能用於在圖上隨機放置金幣,或者計算你是否在一定距離處用步槍擊中目標。

Dim rndGen As New Random()
Dim randomNumber As Integer
randomNumber = rndGen.Next()

上面的程式碼將為你提供一個介於 1 和 2,147,483,647 之間的隨機數。你可能需要一個稍微小的數字。要獲得兩個設定數字之間的隨機數,在本例中為 5 和 10,可以使用以下方法

randomNumber = rndGen.Next(5,10)

那麼我們到底如何使用它呢?看看下面的遊戲

Dim rndGen As New Random()
Dim randomNumber As Integer
Dim guess as Integer
randomNumber = rndGen.Next(1,100)
console.writeline("Please guess the random number between 1 and 100")
Do 
  console.write("your guess:")
  guess = console.readline()
  if guess > randomNumber
    console.writeline("Too High")
  end if
  if guess < randomNumber
    console.writeline("Too Low")
  end if
Loop While guess <> randomNumber
console.writeline("Well done, you took x guesses to find it!")

調整上面的程式碼以告訴使用者他們猜了多少次才找到隨機數。提示:你需要一個變數

答案

    Sub Main()
        Dim rndGen As New Random()
        Dim randomNumber As Integer
        Dim guess As Integer
        Dim count As Integer = 1
        randomNumber = rndGen.Next(1, 100)


        Console.WriteLine("Please guess the random number between 1 and 100")
        Do
            Console.Write("your guess:")
            guess = Console.ReadLine()
            If guess > randomNumber Then
                Console.WriteLine("Too High")
            End If
            If guess < randomNumber Then
                Console.WriteLine("Too Low")
            End If
            If guess <> randomNumber Then
                count = count + 1
            End If
            If guess = randomNumber Then
                Console.WriteLine("Well done, you took " & count & " guesses to find it!")
            End If

        Loop
    End Sub
練習:算術函式

以下程式碼輸出什麼

dim num1 as single = 12.75
dim num2 as single = 12.499
dim total as single

num2 = Math.Round(num2, 1)
num1 = Math.Truncate(num1)
total = num1 + num2
console.writeline(Math.Round(total))

答案

   程式碼輸出

24


編寫一些程式碼以輸出使用者輸入的數字的整數部分

答案

Math.Truncate(input)


編寫程式碼以輸出輸入數字的整數和小數部分

   程式碼輸出

請輸入一個十進位制數字:13.78
這個數字的整數部分是:13
小數部分是:0.78

答案

dim num as single
console.write("Please insert a decimal number: ")
num = console.readline()
console.writeline("The whole number part of this number is: " & Math.Truncate(num))
console.writeline("The decimal part is: " & num - Math.Truncate(num))

字串處理函式

[編輯 | 編輯原始碼]

非常受歡迎的考試問題涉及操縱字串。這些簡單的函式將幫助你完成此任務。

此函式用於查詢傳遞給它的任何字串的長度,包括空格在內的所有字元。在 Visual Basic 中,要查詢字串的長度,我們使用 Len("some string") 函式,該函式返回傳遞給它的字串的整數長度

someText = "Gary had a little lamb"
Console.writeline(Len(someText))
   程式碼輸出

22


此函式允許我們在給定字串中查詢專案的ตำแหน่ง並返回ตำแหน่ง的位置。在 Visual Basic 中,這是透過以下命令執行的:InStr([string], [item]) 例如,我們可能想透過查詢句號來查詢句子結尾的位置

someText = "Gary had a little lamb. His fleece was white as snow."
Console.writeline(InStr(someText,"."))
   程式碼輸出

23

我們也可以使用此命令在字串中搜索字串。例如,如果我們要檢視一個句子是否包含某個名稱

someText = "Gary had a little lamb. Dave's fleece was white as snow."
Console.writeline(InStr(someText,"Dave"))
   程式碼輸出

25

如果搜尋項未包含在字串中,則它將返回 0

someText = "Gary had a little lamb. Dave's fleece was white as snow."
Console.writeline(InStr(someText,"Julie"))
   程式碼輸出

0


子字串

[編輯 | 編輯原始碼]

此函式允許你從字串中剪下專案並返回子字串。Visual Basic 使用以下命令:[string].Substring([startPosition],[lengthOfReturnString])。例如,我們可能想從給定的固定電話號碼中找到本地號碼。我們必須忽略區號

phone = "(01234)567890"
local = phone.Substring(7, 6)
console.writeline(local)
   程式碼輸出

567890


此函式允許你將字串粘合在一起(連線),以便你可以開始使用變數構建字串。Visual Basic 使用以下命令:[stringA & stringB] 例如,我們可能在變數 dim name as string 中儲存了一個使用者的姓名,以及我們想給予他們的問候

name = "Charles"
console.writeline("Hello " & name & ". How are you today?")
   程式碼輸出

你好,查爾斯。今天過得怎麼樣?


字串轉換函式

[編輯 | 編輯原始碼]

當你宣告一個變數時,你給它一個數據型別。此資料型別限制了你可以放入變數的值。例如

dim age as integer
將允許:age = 34
將不允許:age = "cabbages"

這似乎很有道理,但是當你嘗試將一個實數放入整數時會發生什麼

dim age as integer
age = 34.3
console.writeline(age)
   程式碼輸出

34

這似乎沒問題,但是在其他語言中我們可能會遇到麻煩。要執行此操作,我們將不得不從一種資料型別轉換為另一種資料型別

dim age as decimal
age = 34.3
console.writeline(age)
age = CInt(34.3) 'converts the decimal into an integer
console.writeline(age)
   程式碼輸出

34.3 34


練習:字串函式

編寫一個簡短的程式來告訴某人他們姓名中包含多少個字母(以防他們不知道!),例如

   程式碼輸出

輸入:Fremlin
你好,Fremlin,你的名字有 7 個字母。

答案

  Dim name As String
  console.write("Input: ")
  name = console.readline()
  console.writeline("Hello " & name & " you have " & Len(name) & " letters in your name.")


有些人愚蠢地將他們的姓和名輸入到資料庫中,編寫一些程式碼來顯示姓,然後顯示名

Dim name as string = "Elizabeth Sheerin"
   程式碼輸出

輸入:Elizabeth Sheerin
名:Elizabeth
姓:Sheerin

答案

        Dim name As String = "Elizabeth Sheerin"
        Dim firstname, secondname As String
        Dim space, textlength As Integer

        space = InStr(name, " ")
        textlength = Len(name)

        firstname = name.Substring(0, space)
        secondname = name.Substring(space, textlength - space)

        Console.WriteLine("first name is: " & firstname)

        Console.WriteLine("second name is: " & secondname)


電話號碼已作為字串輸入到計算機中:(01234)567890

dim phonenum as string = "(01234)567890"

編寫一些程式碼以輸出不帶括號的號碼

   程式碼輸出

輸入:(01234)567890
輸出:01234567890

答案

        Dim phonenum As String = "(01234)567890"
        Dim firstbracket, secondbracket As String
        Dim textlength, arealength As Integer

        firstbracket = InStr(phonenum, "(")
        secondbracket = InStr(phonenum, ")")
        textlength = Len(phonenum)
        arealength = secondbracket - firstbracket

        Console.Write(phonenum.Substring(firstbracket, arealength - 1) & phonenum.Substring(secondbracket, textlength - secondbracket))


與上面類似的問題,電話號碼目前以一種非常不可讀的格式儲存:01234567890,完全省略了區號。你能將它們轉換為顯示前 5 位數字是區號嗎

dim phonenum as string = "01234567890"

然後應將其輸出為

   程式碼輸出

輸入:01234567890
輸出:(01234)567890

答案

        Dim phonenum As String = "01234567890"
        Console.Write("(" & phonenum.Substring(0, 5) & ")" & phonenum.Substring(6, 5))
        Console.ReadLine()


一個 迴文 是一個可以從任何方向讀作相同的單詞、短語或數字。例如 1234321、RACECAR、TOOT 和 NUN。你需要編寫一個程式來檢查給定的任何輸入是否為迴文,並告知使用者

   程式碼輸出

輸入:NUN
這是一個迴文!
輸入:nune
這不是一個迴文

答案

  Dim name As String
  Dim length As Integer
  Dim Pal As Boolean = TRUE
  console.write("Input: ")
  name = console.readline()
  length = Len(name)
  For x = 0 to (length / 2)
    If name.Substring(x, 1) != name.Substring(length - x, 1) then
       Pal = FALSE
    End If
  Next
  
  If Pal then
    console.writeline("That is a palindrome!")
  Else
    console.writeline("That is NOT a palindrome!")
  End If


擴充套件:REGEX

你通常希望檢查輸入字串的格式,如果格式不正確,則希望重新提交。例如,你可能希望某人輸入他們最好的朋友的姓名,這意味著他們不應該輸入任何數字或空格,並且它應該以大寫字母開頭

   程式碼輸出

最好的朋友的姓名:Beanie(正確)
最好的朋友的姓名:jonny5(停止此操作)

為此,我們可以根據一些規則將輸入字串與一些規則匹配,正則表示式或 regex,在本例中,我們只希望來自字母表的字元

[A-Z][a-z]+

分解規則

  • [A-Z] - 從一個大寫字母開始
  • [a-z]+ - 後面跟著任意數量的小寫字母(+ 表示任意數量)

另一個例子可能是檢查著名作曲家的正確拼寫

"Handel", "Händel", and "Haendel"

我們可以使用模式 H(ä|ae?)ndel 來檢查。讓我們看看這意味著什麼

  • H - 以 H 開頭
  • (ä|ae?) - 包括 ä 或(| 符號)一個 a 後面跟著一個可選的 e (e? 表示 e 是可選的)

大多數正則表示式工具提供以下操作來構建表示式。

布林“或”

豎線分隔備選方案。例如,gray|grey 可以匹配 "gray" 或 "grey"。

分組

括號用於定義運算子的範圍和優先順序(以及其他用途)。例如,gray|greygr(a|e)y 是等效模式,都描述了 "gray" 和 "grey" 的集合。

量化

在標記(如字元)或組後面的量詞指定前面的元素允許出現的次數。

  • ? 問號表示前面的元素出現零次或一次。例如,colou?r 匹配 "color" 和 "colour"。
  • * 星號表示前面的元素出現零次或多次。例如,ab*c 匹配 "ac"、"abc"、"abbc"、"abbbc" 等。
  • + 加號表示前面的元素出現一次或多次。例如,ab+c 匹配 "abc"、"abbc"、"abbbc" 等,但不匹配 "ac"。

大多數程式語言都有正則表示式函式。在 VB.NET 中,我們可以使用 Regex 例程來使用正則表示式

' this code enforces the name rule from earlier
Dim name As String
Console.Write("Name of best friend: ")
name = Console.Readline()

' match the string against a regular expression
Dim m As Match = Regex.Match(name, "[A-Z][a-z]+")

If (m.Success) Then
    Console.WriteLine("You have input the name correctly")
Else
    Console.WriteLine("Incorrect format!")
End If

正則表示式的常見用途是檢查您是否輸入了正確的電子郵件地址。該規則如下:^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$

您可以在維基百科上了解更多關於 正則表示式 的資訊,您將在 A2 中更詳細地學習正則表示式。

到/從整數、實數、日期/時間。

華夏公益教科書