2014-03-19 05:47
题目:给定一个double型浮点数,输出其二进制表示,如果不能在32个字符内完成输出,则输出“ERROR”。
解法:如果你熟悉IEEE754标准,应该知道double和float型的二进制位里都是什么。double型最高位是符号位,随后11位是指数位,之后52位是尾数。你可以根据尾数和指数来判断要用多少二进制位才能精确表示这个浮点数。代码不怎么好写,这种题目应该也不常考吧。
代码:
1 // 5.2 Given a double, print its binary representation if can be done in 32 characters. 2 #include <cstdio> 3 using namespace std; 4 5 void printBinary(unsigned long long num) 6 { 7 unsigned long long bit = 1ull << 63; 8 do { 9 putchar('0' + !!(num & bit)); 10 if ((bit == 1ull << 63) || (bit == 1ull << 52)) { 11 putchar(' '); 12 } 13 bit >>= 1; 14 } while (bit); 15 } 16 17 union un { 18 unsigned long long ull; 19 double d; 20 }; 21 22 int main() 23 { 24 double d; 25 int exp; 26 int ll, rr; 27 int i; 28 unsigned long long sig; 29 un u; 30 31 while (scanf("%lf", &d) == 1) { 32 u.d = d; 33 printBinary(u.ull); 34 putchar(' '); 35 // 1.5 is represented as 1 + 1 * 2^-1, so the '1' must be added to the significant. 36 sig = (u.ull - (u.ull >> 52 << 52)) | (1ull << 52); 37 // exponent has an offset of 127 38 exp = 1022 - (int)(u.ull >> 52 & ~(1ull << 11)); 39 40 ll = 52; 41 rr = 0; 42 while ((sig & (1ull << rr)) == 0) { 43 ++rr; 44 } 45 46 if (ll - rr + 1 + exp <= 30) { 47 // '0.' will take 2 characters, so 30 characters available 48 printf("0."); 49 for (i = 0; i < exp; ++i) { 50 putchar('0'); 51 } 52 for (i = ll;i >= rr; --i) { 53 putchar('0' + !!(sig & (1ull << i))); 54 } 55 putchar(' '); 56 } else { 57 printf("ERROR "); 58 } 59 } 60 61 return 0; 62 }