Cramer规则的IndexOutOfRangeException异常

时间:2016-02-15 18:49:27

标签: arrays vb.net matrix indexing

我目前正在开展一项工作,我必须建立一个能够用Cramer规则解决的程序。但是,似乎我需要构建两个基本矩阵:matA和matB不能因为索引超出范围而我真的看不到哪里。这是代码:

Public Class Form1

    Dim matA(2, 2) As Double
    Dim matB(2, 0) As Double
    Dim matC(2, 2) As Double
    Dim matResultat(0, 2) As Double
    Dim deltaX, deltaY, deltaZ, delta As Double

    Public Function det(ByVal A As Double(,)) As Double

        Dim determinant As Double

        determinant = 0

        For i As Integer = 0 To A.GetUpperBound(0)
            If i = 1 Then
                determinant -= A(0, i) * (A(1, 0) * A(2, 2) - A(2, 0) * A(1, 2))
            ElseIf i = 0 Then
                determinant += A(0, i) * (A(1, 1) * A(2, 2) - A(2, 1) * A(1, 2))
            Else
                determinant += A(0, i) * (A(1, 0) * A(2, 1) - A(2, 0) * A(1, 1))
            End If
        Next

        Return determinant
    End Function

    Public Function solve(ByVal A As Double(,), ByVal B As Double(,)) As Double(,)

        Dim resultat(0, 2) As Double

        matC = A

        For i As Integer = 0 To 2
            For j As Integer = 0 To 2
                matC(j, i) = B(j, i)
            Next
            resultat(0, i) = det(matC)
            matC = A
        Next

        Return resultat
    End Function

    Private Sub ButtonSolve_Click(sender As Object, e As EventArgs) Handles ButtonSolve.Click

        Try
            matA(0, 0) = TBX1.Text
            matA(0, 1) = TBY1.Text
            matA(0, 2) = TBZ1.Text
            matA(1, 0) = TBX2.Text
            matA(1, 1) = TBY2.Text
            matA(1, 2) = TBZ2.Text
            matA(2, 0) = TBX3.Text
            matA(2, 1) = TBY3.Text
            matA(2, 2) = TBZ3.Text

            matB(0, 0) = TBR1.Text
            matB(0, 1) = TBR2.Text
            matB(0, 2) = TBR3.Text
        Catch ex As Exception
            MessageBox.Show(ex.Message)
            MessageBox.Show("Vous devez remplir chaque case avec un nombre entier ou à virgule.")
            Exit Sub
        End Try

        matResultat = solve(matA, matB)

        deltaX = matResultat(0, 0)
        deltaY = matResultat(0, 1)
        deltaZ = matResultat(0, 2)
        delta = det(matA)

        If delta = 0 Then
            MessageBox.Show("Le SEL admet une infinité ou aucune solution.")
        Else
            MessageBox.Show("Le SEL admet une solution unique." & vbCrLf & "X: " & deltaX / delta & vbCrLf & "Y: " & deltaY / delta & vbCrLf & "Z: " & deltaZ / delta)
        End If


    End Sub
End Class

0 个答案:

没有答案