(C语言)实现对任意浮点型数据从十进制到二进制的转换
输入任意字符型数据,并输入小数点保留位数,输出其二进制形式,代码如下:
1#include <stdio.h>
2#include <math.h>
3void printBinaryInt(unsigned long);
4void printBinaryFloat(float,int);
5int main(void)
6{
7 float num;
8 int len;
9 printf("Input the number you want to change:");
10 scanf("%f",&num);
11 printf("\nInput the length after.");
12 scanf("%d",&len);
13
14 printf("\nAfter changed,The result is:");
15 printBinaryFloat(num,len);
16 return 0;
17}
18void printBinaryInt(unsigned long n)
19{
20 int r;
21 r=n%2;
22 if(n>=2)
23 printBinaryInt(n/2);
24 putchar(r?\'1\':\'0\');
25
26 return ;
27}
28void printBinaryFloat(float n,int len)
29{
30 int m;
31 float f;
32 m=(int)n;
33 if(n<0.0)
34 putchar(\'-\');
35 printBinaryInt((int)fabs(n));
36
37 f=fabs((float)(n-(float)m));
38 if(f>0.0)
39 {
40 putchar(\'.\');
41 for(int i=0;i<len;i++)
42 {
43 f*=2.0;
44 //putchar((int)f);
45 printf("%d",(int)f);
46 if(f>=1.0)
47 f-=1.0;
48 }
49 }
50 return ;
51}
2#include <math.h>
3void printBinaryInt(unsigned long);
4void printBinaryFloat(float,int);
5int main(void)
6{
7 float num;
8 int len;
9 printf("Input the number you want to change:");
10 scanf("%f",&num);
11 printf("\nInput the length after.");
12 scanf("%d",&len);
13
14 printf("\nAfter changed,The result is:");
15 printBinaryFloat(num,len);
16 return 0;
17}
18void printBinaryInt(unsigned long n)
19{
20 int r;
21 r=n%2;
22 if(n>=2)
23 printBinaryInt(n/2);
24 putchar(r?\'1\':\'0\');
25
26 return ;
27}
28void printBinaryFloat(float n,int len)
29{
30 int m;
31 float f;
32 m=(int)n;
33 if(n<0.0)
34 putchar(\'-\');
35 printBinaryInt((int)fabs(n));
36
37 f=fabs((float)(n-(float)m));
38 if(f>0.0)
39 {
40 putchar(\'.\');
41 for(int i=0;i<len;i++)
42 {
43 f*=2.0;
44 //putchar((int)f);
45 printf("%d",(int)f);
46 if(f>=1.0)
47 f-=1.0;
48 }
49 }
50 return ;
51}