在 VB 中步进 table 查找?

Stepped table lookup in VB?

我使用书中的这段代码来说明阶梯 table 循环的示例:

Imports System
Imports Microsoft.VisuaLBasic

Public Module Module1

    Public Sub Main()
        Dim rangeLimit() as Double = {50.0, 65.0, 75.0, 90.0, 100.0}
        Dim grade() as String = {"F", "D", "C", "B", "A"}
        Dim maxGradeLevel = grade.length - 1

        Dim gradeLevel = 0
        Dim studentGrade = "A"
        Dim studentScore = 50

        While((studentGrade = "A") and (gradeLevel < maxGradeLevel))
            if(studentScore < rangeLimit(gradeLevel)) then
                studentGrade = grade(gradeLevel)
            End if
            gradeLevel = gradeLevel + 100
        End While
        Print(studentGrade)
    End Sub
End Module

Code is here

我想知道它是如何工作的以及编译后如何修复这个错误:

Run-time exception (line -1): Conversion from string "A" to type 'Integer' is not valid.

您可能需要 Console.WriteLine() 而不是 Print()

还有:

Imports System
Imports System.Linq

Public Module Module1
    Public Sub Main()
        Dim studentScore As Double = 50.0
        Console.WriteLine(GetGrade(studentScore))
    End Sub
    
    Public Function GetGrade(score As Double) As String
        Dim gradeTable = { 
            (50.0,  "F"), 
            (65.0,  "D"), 
            (75.0,  "C"), 
            (90.0,  "B"), 
            (100.0, "A") 
        }
        Return gradeTable.First(Function(g) g.Item1 >= Score).Item2
    End Function
End Module

在这里查看它的工作原理:

https://dotnetfiddle.net/CKTNCE

但就我个人而言,我更喜欢使用最低等级而不是最高等级作为边界。我发现你将分数推到 100 以上的可能性比你得到负分的可能性要大得多,在这种情况下使用最高分会导致问题:

Imports System
Imports System.Linq

Public Module Module1
    Public Sub Main()
        Dim studentScore As Double = 50.0
        Console.WriteLine(GetGrade(studentScore))
    End Sub
    
    Public Function GetGrade(score As Double) As String
        Dim gradeTable = { 
            (90.0, "A"), 
            (75.0, "B"), 
            (65.0, "C"), 
            (50.0, "D"), 
            ( 0.0, "F") 
        }
        Return gradeTable.First(Function(g) g.Item1 >= Score).Item2
    End Function
End Module

您还需要注意相等比较。 >=>是不同的意思,只有一个是正确的。