//Wolfgang Mix - Delphi-PRAXiS
function SolveQuadraticEquation( a, b, c : Double ): MySolution;
var discriminant, re, im: Double;
begin
// ax² + bx + c = 0
if (a = 0)
then
raise Exception.CreateFmt
('
a should not be zero, no quadratic equation',[result.a]);
// calculate discriminant
discriminant := sqr(b)-4*a*c;;
Result.d := discriminant;
// calculate real value
re:=-b/(2*a);
// calculate imaginary value
im:=sqrt(abs(discriminant))/(2*a);
//Form1.Edit7.Text:=FloatToStr(discriminant);
if discriminant > 0
then
begin // 2 solutions
Result.a := -b/(2*a) + sqrt( discriminant)/(2*a);
Result.b := -b/(2*a) - sqrt( discriminant)/(2*a);
Result.c := 1;
end
else
if Math.IsZero(discriminant)
then //needs unit math
begin // 1 solution
Result.a := -b/(2*a);
Result.b := Result.a;
Result.c := 2;
end
else
if discriminant < 0
then
begin // 2 complex solutions
Result.a := re;
Result.b := im;
Result.c := 3;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var a,b,c,discriminant: double;
indicator:integer;
begin
RichEdit1.Lines.Clear;
a:=StrToFloat(Edit1.Text);
b:=StrToFloat(Edit2.Text);
c:=StrToFloat(Edit3.Text);
if (a=0)
then
begin
// Don't calculate
showmessage ('
a should not be zero, no quadratic equation');
sleep(2000);
exit;
end
else
begin
indicator:= SolveQuadraticEquation(a,b,c).c;
case indicator
of
1:
Begin
Label1.Caption:='
2 real solutions';
RichEdit1.Lines.Add ('
X1= ' +
(FloatToStr(SolveQuadraticEquation(a,b,c).a)));
RichEdit1.Lines.Add ('
X2= ' +
(FloatToStr(SolveQuadraticEquation(a,b,c).b)));
End;
2:
Begin
Label1.Caption:='
1 real solution';
RichEdit1.Lines.Add ('
X= ' +
(FloatToStr(SolveQuadraticEquation(a,b,c).a)));
end;
3:
Begin
Label1.Caption:='
2 complex solutions';
RichEdit1.Lines.Add ('
X1= ' +
(FloatToStr(SolveQuadraticEquation(a,b,c).a))+
'
+ ' + FloatToStr(SolveQuadraticEquation(a,b,c).b )+ '
i ');
RichEdit1.Lines.Add ('
X2= ' +
(FloatToStr(SolveQuadraticEquation(a,b,c).a))+
'
- ' + FloatToStr(SolveQuadraticEquation(a,b,c).b )+ '
i ');
End;
end;
discriminant:= SolveQuadraticEquation(a,b,c).d;
Edit4.Text:=FloatToStr(discriminant);
Edit5.Text:=IntToStr(indicator);
end;
end;