如果引用或轉貼,麻煩註明出處與本網誌連結,否則視為侵權。

2014年7月6日

Visual Basic解數學之三 : 使用克拉馬規則(Cramer's Rule)解二元一次方程式

作者: Fred Wang (FW知識瑣記) 日期:2014/7/6

適用版本 : VB 2010~2013
 



功能
1. 二元一次方程式 aX + bY = c, dX + eY = f, 輸入a, b, c, d, e, f求X,Y的值
2. 以克拉馬規則(Cramer's Rule)
    X = ( c * e - b * f ) / ( a * e - b * d )
    Y = ( a * f - c * d ) / ( a * e - b * d ) 
3. 但是  a * e - b * d = 0 時, a * f  - c * d = 0 時無限多解, a * f  - c * d <> 0 時無解



Public Class Form1

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        TextBoxA.Focus()
    End Sub

    Private Sub ButtonExit_Click(sender As Object, e As EventArgs) Handles ButtonExit.Click
        End
    End Sub

    Private Sub ButtonClear_Click(sender As Object, e As EventArgs) Handles ButtonClear.Click
        TextBoxA.Text = ""
        TextBoxB.Text = ""
        TextBoxC.Text = ""
        TextBoxD.Text = ""
        TextBoxE.Text = ""
        TextBoxF.Text = ""
        TextBoxA.Focus()
    End Sub

    Private Sub ButtonRun_Click(sender As Object, e As EventArgs) Handles ButtonRun.Click
        Dim vA, vB, vC, vD, vE, vF, vX, vY As Integer
        If IsNumeric(TextBoxA.Text) And IsNumeric(TextBoxB.Text) And IsNumeric(TextBoxC.Text) And IsNumeric(TextBoxD.Text) And IsNumeric(TextBoxE.Text) And IsNumeric(TextBoxF.Text) Then
            vA = Val(TextBoxA.Text)
            vB = Val(TextBoxB.Text)
            vC = Val(TextBoxC.Text)
            vD = Val(TextBoxD.Text)
            vE = Val(TextBoxE.Text)
            vF = Val(TextBoxF.Text)
            If vA * vE - vB * vD = 0 Then
                If vA * vF - vC * vD = 0 Then
                    TextBoxResult.Text = "無限多解"
                Else
                    TextBoxResult.Text = "無解"
                End If
            Else
                vX = (vC * vE - vB * vF) / (vA * vE - vB * vD)
                vY = (vA * vF - vC * vD) / (vA * vE - vB * vD)
                TextBoxResult.Text = "X = " & CStr(vX) & ", Y = " & CStr(vY)
            End If

        Else
            MsgBox("只能輸入數字", vbOKOnly)
        End If

    End Sub
End Class



上一篇 - Visual Basic解數學之二 : 使用牛頓拉夫森法(Newton-Raphson Method)求平方根近似值

沒有留言:

張貼留言

歡迎提供意見, 謝謝 (註 : 留言經過版主審核通過才會發布)