program DecimalToFraction;
const
Tolerance = 1E-6;
MaxDenominator = 10000;
type
Fraction = record
Numerator: Integer;
Denominator: Integer;
end;
function GCD(a, b: Integer): Integer;
begin
while b <> 0 do
begin
a := a mod b;
a := a + b;
b := a - b;
a := a - b;
end;
GCD := Abs(a);
end;
function DecimalToFraction(decimal: Real): Fraction;
var
n, d, bestN, bestD: Integer;
error, bestError: Real;
begin
bestN := 1;
bestD := 1;
bestError := Abs(decimal - bestN / bestD);
for d := 1 to MaxDenominator do
begin
n := Round(decimal * d);
error := Abs(decimal - n / d);
if error < bestError then
begin
bestN := n;
bestD := d;
bestError := error;
if bestError < Tolerance then
Break;
end;
end;
n := bestN;
d := bestD;
DecimalToFraction.Numerator := n div GCD(n, d);
DecimalToFraction.Denominator := d div GCD(n, d);
end;
var
decimals: array[1..8] of Real = (0.5, 0.3333, 0.25, 0.75, 1.2, -0.4, 3.125, 2.71828);
i: Integer;
frac: Fraction;
begin
Writeln('Decimal to Fraction Conversion:');
Writeln;
for i := 1 to 8 do
begin
frac := DecimalToFraction(decimals[i]);
Write('Decimal: ', decimals[i]:0:5, ' -> Fraction: ');
Writeln(frac.Numerator, '/', frac.Denominator);
end;
end.
(*
run:
Decimal to Fraction Conversion:
Decimal: 0.50000 -> Fraction: 1/2
Decimal: 0.33330 -> Fraction: 3236/9709
Decimal: 0.25000 -> Fraction: 1/4
Decimal: 0.75000 -> Fraction: 3/4
Decimal: 1.20000 -> Fraction: 6/5
Decimal: -0.40000 -> Fraction: -2/5
Decimal: 3.12500 -> Fraction: 25/8
Decimal: 2.71828 -> Fraction: 1264/465
*)