以复杂的形式获得方程的根源

时间:2015-09-11 01:22:40

标签: vb.net equation

我编写了一个代码来解决通过文本框显示根作为输出的二次方程式,但我的程序无法求解导致复数或负根的方程式。如何将这些函数添加到我的程序中。这里是我使用的代码

Public Class Form1     Dim a,b,c As Integer

Dim x1, x2 As Double
Private Sub Label4_Click(sender As Object, e As EventArgs) Handles Label4.Click

End Sub

Private Sub TextBox4_TextChanged(sender As Object, e As EventArgs) Handles eqnRT1.TextChanged

End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles btnExit.Click
    Close()
End Sub

Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
    txtA.Text = ""
    txtB.Text = ""
    txtC.Text = ""
    eqnRT1.Text = ""
    eqnRT2.Text = ""




End Sub

Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
    a = Val(txtA.Text)
    b = Val(txtB.Text)
    c = Val(txtC.Text)
    x1 = Math.Round((-b + Math.Sqrt(b ^ 2 - 4 * a * c)) / (2 * a), 2)
    x2 = Math.Round((-b - Math.Sqrt(b ^ 2 - 4 * a * c)) / (2 * a), 2)
    eqnRT1.Text = x1
    eqnRT2.Text = x2
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

End Sub

结束班

1 个答案:

答案 0 :(得分:0)

您需要添加对System.Numerics的引用,并使用Complex结构进行计算。

试试这个:

Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
    Dim a = New System.Numerics.Complex(Double.Parse(txtA.Text), 0.0)
    Dim b = New System.Numerics.Complex(Double.Parse(txtB.Text), 0.0)
    Dim c = New System.Numerics.Complex(Double.Parse(txtC.Text), 0.0)
    Dim x1 = (-b + System.Numerics.Complex.Sqrt(b * b - 4 * a * c)) / (2 * a)
    Dim x2 = (-b - System.Numerics.Complex.Sqrt(b * b - 4 * a * c)) / (2 * a)
    eqnRT1.Text = String.Format("{0:0.00}+{1:0.00}i", x1.Real, x1.Imaginary)
    eqnRT2.Text = String.Format("{0:0.00}+{1:0.00}i", x2.Real, x2.Imaginary)
End Sub

这也是一个好主意,养成只为了显示目的进行舍入并保持所有计算不受所有舍入影响的习惯。

并且,如果您没有在类中共享值,最好在它们正在使用的方法中声明变量。