誰有把小數轉化成分數形式表示的函數?(50分)

  • 主题发起人 主题发起人 P_W_Q
  • 开始时间 开始时间
P

P_W_Q

Unregistered / Unconfirmed
GUEST, unregistred user!
誰有把小數轉化成分數形式表示的函數?
 
例如:0.75變成3/4 ,0.125變成1/8
 
????
真有这样的需求?
0.5=1/2=2/4=3/6=.....你要的最简的吧
 
to:sunsong
的確有這樣的需求, 不錯, 是要最簡的!
 
function FloatToFraction(Value: Double): string;
const
e = 1e-5;
var
a, b: Integer;
i: Integer;
begin
Result:=IntToStr(Trunc(Value));
Value:=Frac(Value);
if Value>e then
begin
Result:=Result+'又';
a:=Round(Value*100000);
b:=100000;
for i:=2 to Trunc(sqrt(a)) do
while (a mod i=0) and (b mod i=0) do
begin
a:=a div i;
b:=b div i
end;
Result:=Result+IntToStr(a)+'/'+IntToStr(b)
end
end;
 
to:leechage
正確! 結貼!
 
多人接受答案了。
 
unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type
TForm1 = class(TForm)
Edit1: TEdit;
Button1: TButton;
Label1: TLabel;
procedure Button1Click(Sender: TObject);
procedure Edit1KeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
function lcdiv(i,j:integer):integer;
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var s:string;
i:integer;
div1,div2:integer;
begin
s:=edit1.Text;
i:=pos('.',s);
s:=copy(s,i+1,length(s));
div2:=length(s);
div1:=strtoint(s);
div2:=strtoint(Floattostr(exp(div2*ln(10))));
i:=lcdiv(div1,div2);
label1.Caption:=inttostr(div1 div i)+#13+'-'+#13+inttostr(div2 div i);
end;

function TForm1.lcdiv(i,j:integer):integer;
var d,x,g:integer;
begin
if i<j then
begin
d:=j;
x:=i;
end
else
begin
d:=i;
x:=j;
end;
repeat
g:=d mod x;
d:=x;
x:=g;
until g=0;
result:=d;
end;

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
if not(key in ['0'..'9','.',#8]) then key:=#0;
end;

end.
 
謝謝支援, 分沒有了!
 

Similar threads

S
回复
0
查看
652
SUNSTONE的Delphi笔记
S
S
回复
0
查看
676
SUNSTONE的Delphi笔记
S
S
回复
0
查看
1K
SUNSTONE的Delphi笔记
S
后退
顶部