从十进制数中获取一个分数

Alb*_*ola 2 delphi math

我正在开发一个解决方程组的程序.当它给我结果时,它就像:"x1 = 1,36842".我想得到"1,36842"的一小部分,所以我写了这段代码.

procedure TForm1.Button1Click(Sender: TObject);
var numero,s:string;
    a,intpart,fracpart,frazfatta:double;
    y,i,mcd,x,nume,denomin,R:integer;
begin
 a:=StrToFloat(Edit1.Text);  //get the value of a
 IntPart := Trunc(a);        // here I get the numerator and the denominator
 FracPart := a-Trunc(a);
 Edit2.Text:=FloatToStr(FracPart);
 numero:='1';
 for i:= 1 to (length(Edit2.Text)-2) do
 begin
  numero:=numero+'0';
 end;                       //in this loop it creates a string that has many 0 as the length of the denominator
 Edit3.text:=FloatToStr(IntPart);
 y:=StrToInt(numero);
 x:=StrToInt(Edit3.Text);
 while y <> 0 do
 begin
  R:= x mod y;
  x:=y;
  y:=R;
 end;
 mcd:=x;              //at the end of this loop I have the greatest common divisor
 nume:= StrToInt(Edit3.Text) div mcd;
 denomin:= StrToInt(numero) div mcd;
 Memo1.Lines.Add('fraction: '+IntToStr(nume)+'/'+IntToStr(denomin));
end;
Run Code Online (Sandbox Code Playgroud)

它无法正常工作,因为它给我的分数是错误的.有人可以帮帮我吗?

Dav*_*nan 5

您的代码无法正常工作,因为您使用的是二进制浮点数.二进制浮点类型不能表示您尝试表示的十进制数.可表示的二进制浮点数的形式为s2 e,其中s是有效数,e是指数.因此,例如,您不能将0.1表示为二进制浮点值.

最明显的解决方案是使用整数运算执行计算.根本不要调用StrToFloat.不要触摸浮点运算.自己解析输入字符串.找到小数点.使用后面的位数来计算小数位.剥去任何前导或尾随零.并使用整数运算来完成剩下的工作.

例如,假设输入是'2.79'.通过处理文本将其转换为分子和分母变量

Numerator := 279;
Denominator := 100;
Run Code Online (Sandbox Code Playgroud)

显然你必须编写字符串解析例程而不是使用整数文字,但那是常规的.

最后,通过找到这两个整数的gcd来完成问题.

最重要的是,要表示和操作十进制数据,您需要一个十进制算法.这不包括二进制浮点数.