天天看點

執行個體006查找随機數組中質數的個數Visual Basic 中的數組Array 類VBMath.Randomize 方法VBMath.Rnd 方法Conversion.Int 方法NET 中的格式類型

Visual Basic 中的數組

https://docs.microsoft.com/zh-cn/dotnet/visual-basic/programming-guide/language-features/arrays/#the-array-type

Array 類

https://docs.microsoft.com/zh-cn/dotnet/api/system.array?view=netframework-4.8

VBMath.Randomize 方法

https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.visualbasic.vbmath.randomize?view=netframework-4.8

VBMath.Rnd 方法

https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.visualbasic.vbmath.rnd?view=netframework-4.8#Microsoft_VisualBasic_VBMath_Rnd

Conversion.Int 方法

https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.visualbasic.conversion.int?view=netframework-4.8

NET 中的格式類型

https://docs.microsoft.com/zh-cn/dotnet/standard/base-types/formatting-types

控制台程式

Module Module1

    Sub Main()

        '源數組

        Dim scArray(20) As Integer

        '找到的結果數組

        Dim resPArray(0) As Integer

        'MsgBox(scArray.GetUpperBound(0)),擷取數組第一維的最大下标,比元素個數小1

        'MsgBox(scArray.GetLength(0)),擷取數組第一維長度

        '循環計數

        Dim icount As Integer

        '儲存生成的随機數

        Dim Rnds As Integer

        '随機種子

        Randomize()

        Console.WriteLine("生成21個2到10000間随機數")

        For icount = 0 To 20

            Rnds = Int(Rnd() * 9998 + 2)

            '等價天scArray(icount)=Rnds

            scArray.SetValue(Rnds, icount)

            'scArray.GetValue(icount)等價于scArray(icount)

            Console.Write(Convert.ToString(scArray.GetValue(icount)) & ", ")

        Next

        Console.WriteLine()

        '找質數

        For icount = 0 To 20

            If IsPrimeNumber(scArray.GetValue(icount)) Then

                ReDim Preserve resPArray(resPArray.GetUpperBound(0) + 1)

                resPArray.SetValue(scArray.GetValue(icount), resPArray.GetUpperBound(0))

            End If

        Next

        '結果

        Console.WriteLine("數列中的質數有:{0:###}個", resPArray.GetLength(0) - 1)

        For icount = 1 To resPArray.GetUpperBound(0)

            Console.Write(resPArray.GetValue(icount))

            Console.Write(". ")

        Next

        Console.ReadLine()

    End Sub

    '判斷質數

    Public Function IsPrimeNumber(ByVal pNumber As Integer) As Boolean

        Dim iFactor As Integer

        For iFactor = 2 To Int(Math.Sqrt(pNumber))

            If pNumber Mod iFactor = 0 Then

                Return False

            End If

        Next

        Return True

    End Function

End Module