十进制实数转二进制的程序
来源:学生作业帮 编辑:大师作文网作业帮 分类:综合作业 时间:2024/11/11 22:47:26
十进制实数转二进制的程序
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.
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.
再问: 把这个程序改为十进制实数转二进制数
再答: 由于十进制小数转化为二进制小数通常都是无限循环小数,所以下面最多输出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.