十进制实数转二进制的程序

问题描述:

十进制实数转二进制的程序
Program zy6;
var bin:array [0..50] of 0..1;
x:longint;
k,i:integer;
begin
writeln('read decimal data x:'); read(x);
for i:=0 to 50 do bin[i]:=0;
k:=0;
while x>0 do
begin
bin[k]:=x mod 2;x:=x div 2;
k:=k+1;
end;
writeln('Binary:');
for i:=k-1 downto 0 do write(bin[i]:1);
end.

你这是整数的转换程序啊.

由于十进制小数转化为二进制小数通常都是无限循环小数,所以下面最多输出50位二进制小数(可以修改为你想要的位数。

{$N+}                                            {在Free Pascal下不需要此行}

var bin:array [0..31] of 0..1;

    y:double; x:longint;

    k,i:integer;

begin

    writeln('read decimal data x:'); read(y);

    for i:=0 to 50 do bin[i]:=0;

    k:=0; x:=trunc(y); y:=y-x;

    while x>0 do

       begin

            bin[k]:=x mod 2;x:=x div 2;

            k:=k+1;

       end;

    writeln('Binary:');

    for i:=k-1 downto 0 do write(bin[i]:1);

    i:=0; write('.');

    while (y>1e-10)and(i<50) do            {这里规定最多50位小数}

    begin

      y:=y*2; inc(i);

      if y>=1 then begin write(1); y:=y-1 end else write(0);

    end;

    writeln;

end.