二次方程程序出错

时间:2014-07-30 11:08:17

标签: vb.net

我已经制作了一个解决二次方程的程序,除了当平方根中的部分小于0时它工作正常。当发生这种情况时,我希望它显示没有根。这是我目前正在使用的代码。

 SquareRoot = System.Math.Sqrt((B ^ 2) - (4 * A * C))

   If SquareRoot < 0 Then
        lblRoot1.Text = "No Root"
        lblRoot2.Text = "No Root"

然而,尽管如此,如果我在这种情况下运行程序,它会崩溃。我该如何解决? (请保持答案尽可能简单,因为我还是初学者)

3 个答案:

答案 0 :(得分:0)

你的问题是你正在检查负值的错误。负数的平方根是虚数,这是代码崩溃时得到的错误。相反,将检查移动到行列式,就像这样(这只是伪代码):

IF (B * B) - (4 * A * C) < 0
    lblRoot1.Text = "No Root"
    lblRoot2.Text = "No Root"

ELSE
    SquareRoot = System.Math.Sqrt((B * B) - (4 * A * C))

为方便起见,您可能需要创建一个变量来保存行列式计算,如下所示:

Dim D As Integer = (B * B) - (4 * A * C) 'Use appropriate datatype instead of Integer

答案 1 :(得分:0)

为什么不简单地使用临时变量:

Dim value = (B ^ 2) - (4 * A * C)
If value < 0 Then
  ' error handling
Else
  Dim SquareRoot = System.Math.Sqrt(value)
End If

答案 2 :(得分:0)

调试程序时,应该会看到异常发生在行

SquareRoot = System.Math.Sqrt((B ^ 2) - (4 * A * C))

原因是你不允许对Sqrt使用负输入值(没有“负”平方根,不能用数学方法)所以你需要做这样的事情:

Input = (B ^ 2) - (4 * A * C)
If Input >= 0 Then
    SquareRoot = System.Math.Sqrt(Input)
Else
    lblRoot1.Text = "No Root"
    lblRoot2.Text = "No Root"
相关问题