Quadratic equation in Ada
Example for versions
gnat 3.4.5,
gnat 4.3.2
Ada provides complex datatype, which requires using packages Generic_Complex_Types and Generic_Complex_Elementary_Functions and instantiating them with the type of complex number to use (in this case — floating-point numbers). Ada doesn’t support implicit data type conversions, so all casts are done explicitly.
with Ada.Text_IO,
Ada.Integer_Text_IO,
Ada.Float_Text_IO,
Ada.Numerics.Elementary_Functions,
Ada.Text_IO.Complex_IO,
Ada.Numerics.Generic_Complex_Types,
Ada.Numerics.Generic_Complex_Elementary_Functions;
use Ada.Text_IO, Ada.Integer_Text_IO, Ada.Float_Text_IO;
procedure QuadraticEquation is
package Complex_Types is new Ada.Numerics.Generic_Complex_Types (Float);
package Complex_Functions is new Ada.Numerics.Generic_Complex_Elementary_Functions(Complex_Types);
package Complex_IO is new Ada.Text_IO.Complex_IO (Complex_Types);
use Complex_Types, Complex_Functions, Complex_IO;
A,B,C,D: Integer;
A2f, Bf, S: Float;
Dc: Complex;
begin
Put("A = ");
Get(Item => A);
if A = 0 then
Put_Line("Not a quadratic equation.");
return;
end if;
Put("B = ");
Get(B);
Put("C = ");
Get(C);
A2f := Float(2*A);
Bf := Float(B);
D := B*B-4*A*C;
if D = 0 then
Put("x = ");
Put(-Bf/A2f);
elsif D > 0 then
S := Ada.Numerics.Elementary_Functions.Sqrt(Float(D));
Put("x1 = ");
Put((-Bf+S)/A2f);
Put_Line("");
Put("x2 = ");
Put((-Bf-S)/A2f);
else
Dc := Compose_From_Cartesian (Re => Float(D), Im => 0.0);
Put("x1 = ");
Put((-Bf+Complex_Functions.Sqrt(Dc))/A2f);
Put_Line("");
Put("x2 = ");
Put((-Bf-Complex_Functions.Sqrt(Dc))/A2f);
end if;
end QuadraticEquation;
Comments
]]>blog comments powered by Disqus
]]>