excel VBA不使用函数求中值

mklgxw1f  于 2022-11-26  发布在  其他
关注(0)|答案(1)|浏览(126)

我试着不使用函数来求中值但我不知道我做错了什么。

Dim i As Integer
Dim passNum As Integer
Dim temp As Integer
Dim aantal As Integer
Dim n(1 To 50) As Single
Dim p As Integer
Dim j As Single
Dim t As Single
Dim median As Single

aantal = InputBox("how many n variables do you want max 50")

For p = 1 To aantal
    n(p) = InputBox("geef " & aantal & " nummers")
Next



'Rem bubble sort names
    For passNum = 1 To aantal - 1
        For i = 1 To aantal - passNum
            If n(i) < n(i + 1) Then
                temp = n(i)
                n(i) = n(i + 1)
                n(i + 1) = temp
            End If
        Next i
Next passNum
'Rem display alphabetized list
For i = 1 To aantal
    Worksheets(1).Cells(i, 1) = n(i)
Next i

'find the median

t = aantal Mod 2

If t > 0 Then
    median = n(aantal + 1) / 2
Else
    median = (n(aantal / 2) + (n(aatnal) / 2) + 1) / 2
    
End If

    Worksheets(1).Cells(1, 2) = median

End Sub

这是我现在的代码,但是它找不到中间值,其他的一切都很好。
我试过把n(aantal)换成别的东西,但也不管用,要么给我错误的数字,要么什么都没有。

wxclj1h5

wxclj1h51#

也许可以试试这个:

Sub Median()

    Dim i As Integer
    Dim aantal As Integer, tmp as double
    ReDim n(0) As Double

100:        
    aantal = InputBox("how many n variables do you want max 50")
    If aantal > 50 Then Goto 100
    
    ReDim n(aantal - 1)
    For i = 0 To UBound(n)
        n(i) = CDbl(InputBox("Geef nr " & i + 1 & " van " & aantal & " nummers"))
    Next
    
    For i = LBound(n) To UBound(n)
        For j = i + 1 To UBound(n)            
            If n(i) > n(j) Then
                tmp = n(j)
                n(j) = n(i)
                n(i) = tmp
            End If
        Next
    Next
    
    m = aantal Mod 2
    ix = ((aantal + m) / 2) - 1
    If (m = 1) Then
        nMedian = n(ix)
    Else
        nMedian = (n(ix) + n(ix + 1)) / 2
    End If
    
    Debug.Print nMedian        
    
End Sub

相关问题