gpt4 book ai didi

delphi - 从它的十进制数中得到一个分数

转载 作者:行者123 更新时间:2023-12-03 18:08:21 24 4
gpt4 key购买 nike

我正在开发一个求解方程组的程序。当它给我结果时,就像:“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;

它不能正常工作,因为它给我的分数是错误的。谁能帮帮我?

最佳答案

您的代码无法运行,因为您使用的是二进制 float 。二进制浮点类型不能表示您要表示的十进制数。可表示的二进制 float 的形式为 s2e,其中 s 是有效数,e 是指数。因此,例如,您不能将 0.1 表示为二进制浮点值。

最明显的解决方案是使用整数运算执行计算。根本不要调用 StrToFloat。不要接触浮点运算。自己解析输入字符串。找到小数点。使用后面的位数来计算十进制。去掉任何前导或尾随零。剩下的使用整数运算。

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

Numerator := 279;
Denominator := 100;

显然,您必须编写字符串解析例程而不是使用整数文字,但这是例行程序。

最后,求出这两个整数的gcd来完成本题。

最重要的是,要表示十进制数据并对其进行操作,您需要一种十进制算法。这不包括二进制 float 。

关于delphi - 从它的十进制数中得到一个分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15753273/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com