2次方程式の解の公式をそのまま使うと、|b| ≒ √(b^2 - 4ac)のとき桁落ちが生じる。 そこで、桁落ちの生じないほうの解だけ公式で求め、もう一方は解と係数の関係(解をα、βとするとαβ = c / a)で求める。

quadeq.cの移植 AB4.24.00で動作確認

#strict
#prompt

Dim a As Double, b As Double, c As Double, d As Double, x As Double

Print "Input a, b, c"
Input a, b, c

If a <> 0 Then
' aで割ってx^2 + b*x + c = 0の形にする
b /= a
c /= a
If c <> 0 Then
b /= 2 ' x^2 + 2b'x + c = 0
d = b * b - c ' 判別式 D / 4
If d > 0 Then
If b > 0 Then
x = -b - Sqr(d)
Else
x = -b + Sqr(d)
End If
Print "x = "; x; ", "; c / x
ElseIf d < 0 Then
Print "x = "; -b; " +- "; Sqr(-d); "i"
Else
Print "x = ", -b
End If
Else
Print "x = "; -b; ", 0"
End If
ElseIf b <> 0 Then
Print "x = "; -c / b
ElseIf c <> 0 Then
Print "解なし。"
Else
Print "不定。"
EndIf