編碼新手。上週我有一個項目要求用戶輸入4個等級,然後計算所有4個等級的平均值,並且最低等級的平均值下降(已經轉換成btw)。要求是For Next循環和Do While循環來計算平均值。我使用For Next循環來獲得4個等級的總和,然後計算平均值。需要VB做... while循環來計算平均值
Declare variables, constant, and array
Const intMAX_SUBSCRIPT As Integer = 3
Dim intGrades(intMAX_SUBSCRIPT) As Integer
Dim intTotal As Integer = 0 'holds the total of grades
Dim dblAverage As Double 'holds the average of all 4 grades
Dim intCount As Integer 'loop counter
Dim intLowest As Integer 'holds the lowest score
'assign grades to array slots
intGrades(0) = CInt(txtGrade1.Text)
intGrades(1) = CInt(txtGrade2.Text)
intGrades(2) = CInt(txtGrade3.Text)
intGrades(3) = CInt(txtGrade4.Text)
'Loop to calculate average in grades array
'get total of all grades
For intCount = 0 To (intGrades.Length - 1)
intTotal += intGrades(intCount)
Next
'use floating-point div to find average
dblAverage = intTotal/intGrades.Length
這工作正常。然後我用以下找到最低年級:
intLowest = intGrades(0)
'Search for the lowest grade in the array
For intCount = 1 To (intGrades.Length - 1)
If intGrades(intCount) < intLowest Then
intLowest = intGrades(intCount)
End If
Next
這也工作,因爲它應該。現在,我遇到了這個問題:做一個儘管計算新的平均值與最低的分數下降。這是我需要幫助的地方:
Dim intNewTotal As Integer = 0 'holds the new total of the 3 highest grades
Dim dblNewAverage As Double 'holds the new average with the lowest score dropped
Dim intNewCount As Integer = 0 'loop counter
Do While intNewTotal <= (intTotal - intLowest)
intNewTotal = intNewTotal + intGrades.Length - 1
intNewCount += 1
Loop
dblNewAverage = intNewTotal/3
數學很接近但並不完全。對於100,100,80和100的分數,我得到以下結果:所有4的平均值= 95,最低分數下降的平均值= 101.新的平均值總是比它應該高一個。我能做些什麼來解決這個問題?我真的很想理解,所以如果它再次發生,我可以解決這個問題。謝謝!
如果通過與調試器單步執行代碼(DO上設置一個斷點雖然intNewTotal <=(intTotal - intLowest)),你會看到你的價值之一是他們應該不是什麼。從那裏倒退。 – Mathemats 2015-04-02 01:38:00