一千萬個為什麽

搜索

使用vb.net在數組中查找最小值和最大值

我需要在數組中找到最小值和最大值。 .max 函數可以工作,但 .min 會一直顯示為零。

Public Class Program_2_Grade
    Dim max As Integer
    Dim min As Integer
    Dim average As Integer
    Dim average1 As Integer
    Dim grade As String
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If TextBox1.Text = Nothing Or TextBox1.Text > 100 Then
            MsgBox("Doesn't Meet Grade Requirements", MsgBoxStyle.Exclamation, "Error")
            TextBox1.Clear()
            TextBox1.Focus()
            counter = 0
        Else
            grade_enter(counter) = TextBox1.Text
            TextBox1.Clear()
            TextBox1.Focus()
            counter = counter + 1

            If counter = grade_amount Then
                max = grade_enter.Max()
                min = grade_enter.Min()

                For i As Integer = 0 To counter
                    average = average + grade_enter(i)/counter
                    average1 = average1 + grade_enter(i) - grade_enter.Min/counter
                Next

                Select Case average
                    Case 30 To 49
                        grade = "C"
                    Case 50 To 69
                        grade = "B"
                    Case 70 To 100
                        grade = "A"
                    Case Else
                        grade = "Fail"
                End Select

                If (Program_2.CheckBox1.Checked = True) Then
                    Program_2.TextBox4.Text = _
                ("Name:" & " " & (Program_2.TextBox1.Text) & vbNewLine & _
                "Class: " & (Program_2.TextBox2.Text) & vbNewLine & _
                "Number Of Grades:" & " " & (Program_2.TextBox3.Text) & vbNewLine & _
                "Max:" & " " & max & vbNewLine & _
                "Min:" & " " & min & vbNewLine & _
                "Average:" & " " & average1 & vbNewLine) & _
                "Grade:" & " " & grade & vbNewLine & _
                "Dropped Lowest Grade"
                Else
                    Program_2.TextBox4.Text = _
                ("Name:" & " " & (Program_2.TextBox1.Text) & vbNewLine & _
                "Class: " & (Program_2.TextBox2.Text) & vbNewLine & _
                "Number Of Grades:" & " " & (Program_2.TextBox3.Text) & vbNewLine & _
                "Max:" & " " & max & vbNewLine & _
                "Min:" & " " & min & vbNewLine & _
                "Average:" & " " & average & vbNewLine) & _
                "Grade:" & " " & grade & vbNewLine
                End If

                Me.Close()
                average = 0
                average1 = 0
                counter = 0
            End If
        End If
    End Sub

我的數組設置在全局範圍內。

最佳答案

您尚未顯示正在創建grade_enter的位置。我的猜測是它比需要的大,所以當你試圖找到最小值時,會有“空”條目(值為0)。

您可以將其更改為:

max = grade_enter.Take(counter).Max()
min = grade_enter.Take(counter).Min()

作為一種讓它工作的方法,但最好使用適當的空間開始(或 List(Of Integer))。

轉載註明原文: 使用vb.net在數組中查找最小值和最大值