转载自http://bbs.csdn.net/topics/390676437
用10进制小数不能精确表示某些三进制小数0.1(3)=0.33333333333……(10)
同理,用二进制小数也不能精确表示某些10进制小数。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
int
main() {
float
f;
double
d;
char
bs[65];
char
b[65];
char
s[80];
unsigned
char
*p;
char
e[12];
char
*t;
int
ex;
while
(1) {
printf
(
"Input a float point number:"
);
fflush
(stdout);
rewind
(stdin);
fgets
(s,80,stdin);
if
(1==
sscanf
(s,
"%f"
,&f) && 1==
sscanf
(s,
"%lf"
,&d))
break
;
}
printf
(
"f=%g\n"
,f);
p=(unsigned
char
*)&f;
printf
(
"hex=%02X %02X %02X %02X\n"
,p[3],p[2],p[1],p[0]);
ltoa(*(
long
*)&f,b,2);
sprintf
(bs,
"%032s"
,b);
printf
(
"bin=%s\n"
,bs);
printf
(
"bin=%.1s %.8s %s\n"
,bs,bs+1,bs+9);
strncpy
(e,bs+1,8);e[8]=0;
ex=
strtol
(e,&t,2);
printf
(
" %c %-4d-127 1.%s\n"
,(bs[0]==
'0'
)?
'+'
:
'-'
,ex,bs+9);
ex-=127;
printf
(
" %c %-8d 1.%s\n"
,(bs[0]==
'0'
)?
'+'
:
'-'
,ex,bs+9);
printf
(
"\nd=%lg\n"
,d);
p=(unsigned
char
*)&d;
printf
(
"hex=%02X %02X %02X %02X %02X %02X %02X %02X\n"
,p[7],p[6],p[5],p[4],p[3],p[2],p[1],p[0]);
_i64toa(*(
__int64
*)&d,b,2);
sprintf
(bs,
"%064s"
,b);
printf
(
"bin=%s\n"
,bs);
printf
(
"bin=%.1s %.11s %s\n"
,bs,bs+1,bs+12);
strncpy
(e,bs+1,11);e[11]=0;
ex=
strtol
(e,&t,2);
printf
(
" %c %-6d-1023 1.%s\n"
,(bs[0]==
'0'
)?
'+'
:
'-'
,ex,bs+12);
ex-=1023;
printf
(
" %c %-11d 1.%s\n"
,(bs[0]==
'0'
)?
'+'
:
'-'
,ex,bs+12);
return
0;
}
//Input a float point number:0.125
//f=0.125
//hex=3E 00 00 00
//bin=00111110000000000000000000000000
//bin=0 01111100 00000000000000000000000
// + 124 -127 1.00000000000000000000000
// + -3 1.00000000000000000000000
//
//d=0.125
//hex=3F C0 00 00 00 00 00 00
//bin=0011111111000000000000000000000000000000000000000000000000000000
//bin=0 01111111100 0000000000000000000000000000000000000000000000000000
// + 1020 -1023 1.0000000000000000000000000000000000000000000000000000
// + -3 1.0000000000000000000000000000000000000000000000000000
//
|