0

我的问题是当我输入四个测试的分数时:1 2 3 3,它计算总和平均一切都很好,但是如果我输入大于 3 的测试分数,它比我的数组大,它会给我这个函数的错误

Public Function TotalScore(studentScore() As Integer, intTotalScore As Integer) As Integer
    For Each i As Integer In studentScore
        intTotalScore += studentScore(i)
    Next
    Return intTotalScore
End Function 

错误信息是index is out of range array。很抱歉,如果您需要其他代码或更多详细信息,我将非常乐意提供,我不知道如何更好地解释它。感谢您的时间

 Public g_intTotalScore As Integer                                                       'total score
 Public g_decAverageScore As Decimal                                                     'average score
 Public g_strLetterScore As String
 Public Const intMAX_SUBSCRIPT_STUDENTS_NAMES As Integer = 4                            'max subscript for students names 
 Public Const intMAX_SUBSCRIPT_SCORE As Integer = 3                                      'max subscript for student numeric scores on 4 test

Public strStudentsNames(intMAX_SUBSCRIPT_STUDENTS_NAMES) As String                 'array that holds students names
Public strLetterGrades() As String = {"A", "B", "C", "D", "F"}                     'array that hold letter grades
Public intStudent1(intMAX_SUBSCRIPT_SCORE) As Integer                              'hold test scores for student1

我创建了接受两个参数的函数来计算 4 次测试的总分

Public Function TotalScore(studentScore() As Integer, intTotalScore As Integer) As Integer
    For Each i As Integer In studentScore
        intTotalScore += studentScore(i)
    Next
    Return intTotalScore
End Function

这是学生姓名和超过 4 个测试分数的输入

Do While intCount < strStudentsNames.Length
    'input data for student number1
    If intCount = 0 Then
        intCounter = 0
        strStudentsNames(intCount) = InputBox("Enter Student Name number" &       intCount + 1, "Enter Data")
        Do While intCounter < intStudent1.Length
            intStudent1(intCounter) = CInt(InputBox("Student Name: " & strStudentsNames(intCount) & vbCrLf &
                                                    "Enter Score for test number " & intCounter + 1, "Enter Data"))
            intCounter += 1
        Loop
    End If
    intCount += 1
Loop

这是要列出的显示数据

'student1: calculate total , avaerage score, display average score, reset total score
g_intTotalScore = TotalScore(intStudent1, g_intTotalScore)
g_decAverageScore = Average(g_decAverageScore)
lstOutPut.Items.Add("Student Name: " & strStudentsNames(0) & " => The average score is: " & g_decAverageScore.ToString & " => Grade: ")
g_intTotalScore = 0
4

1 回答 1

0

该错误意味着您试图从数组索引中获取数组中不存在的东西。例如,该数组有 10 个元素,索引为 0 - 9,您调用的索引号为 11。

尝试像这样使用 for each:

For Each i As Integer In studentScore
        intTotalScore += i
Next
于 2013-11-06T08:46:36.887 回答