簡體   English   中英

如何找到3個整數之間的最大整數

[英]How to find the largest integer(s) between 3 integers

我想找到3個整數之間的最大整數。

我可以通過嵌套If語句來做到這一點。 由於我還有其他代碼要編寫,所以這將很長且不整潔。

我想知道是否有一種更簡單的方法來找到最大整數(包括假設AB相等但都大於C )。

PS,您可以使用二維陣列嗎?

使用LINQ可以做到這一點:

Dim numbers() As Integer = {1, 3, 5}

Dim max As Integer = numbers.Max()

Debug.Write("Max number in numbers() is " & max.ToString())

輸出:

在此處輸入圖片說明

根據與OP的對話進行編輯,希望了解哪種流派排名最高。

當被問到如何獲取數據? OP回應:

我的每一行都有一個包含movie | genre的文本文件。 我讀了此書,然后算出哪一類(最高3種)。

我已經草擬了一些從文本文件讀取並填充類的代碼。

首先讓我向您展示代碼:

Dim myFilms As New Films

Using sr As New IO.StreamReader("C:\films.txt")

    Do Until sr.Peek = -1

        Dim columns As String() = sr.ReadLine().Split(New Char() {"|"c}, StringSplitOptions.RemoveEmptyEntries)

        'columns(0) = film name
        'columns(1) = genre
        myFilms.Add(New Film(columns(0), columns(1)))
    Loop

End Using

If myFilms.Count > 0 Then
    Dim bestGenre = myFilms.GetBestGenre()

    'Go off and read the genre file based on bestGenre
End If

從上面的代碼中,您可以看到正在使用新Film填充的Films類。 然后,我從Films類中調用一個方法,但前提是要選擇電影。 讓我向您展示這兩個類的類結構:

電影:

Public Class Film
    Public Key As String

    Public Sub New(ByVal filmName As String,
                   ByVal genre As String)

        _filmName = filmName
        _genre = genre

    End Sub

    Private _filmName As String
    Public ReadOnly Property FilmName As String
        Get
            Return _filmName
        End Get
    End Property

    Private _genre As String
    Public ReadOnly Property Genre As String
        Get
            Return _genre
        End Get
    End Property

End Class

電影:

Public Class Films
    Inherits KeyedCollection(Of String, Film)

    Protected Overrides Function GetKeyForItem(ByVal item As Film) As String
        Return item.Key
    End Function

    Public Function GetBestGenre() As String

        Return Me.GroupBy(Function(r) r.Genre).OrderByDescending(Function(g) g.Count()).First().Key

    End Function

End Class

我必須注意,盡管此代碼確實有效,但如果您具有2種或更多類型的聯合排行榜,則可能會出現問題。 該代碼仍然有效,但是僅返回其中一種類型。 您可能需要根據該情況擴展代碼以適合您的需求。

嘗試這樣的事情:

Dim max As Integer
max = integer1

If integer2 > max Then
   max = integer2
End If

If integer3 > max Then
   max = integer3
End If 

我沒有想到的很多方法可以做到這一點。

這些線適用於任意數量的整數。 將數字放入數組中,然后使用For[...]Next語句遍歷數組,將當前成員與max進行比較。 如果max較低,則將其設置為當前成員。 循環終止時, max將包含最大數:

Dim nums() As Integer = {1, 2, 3}
Dim max As Integer

For i = 0 To nums.Length - 1
    If max < nums(i) Then
        max = nums(i)
    End If
Next

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM