面试金典--5.2

题目描述:打印double类型,且在0~1之间的数的二进制表示

思路:每次乘以2,相当于左移1位,判断当前位是0还是1。

 1 #include <iostream>
 2 #include <string>
 3 #include <fstream>
 4 #include <map>
 5 #include <algorithm>
 6 #include <vector>
 7 #include <ctime>
 8 #include <bitset>
 9 #include <stack>
10 
11 using namespace std;
12 
13 int main()
14 {
15     double f;
16     cin>>f;
17     if(f>=1 || f<=0)
18     {
19         cout<<"ERROR"<<endl;
20     }
21     else
22     {
23         string s;
24         while(f>0)
25         {
26             if(s.length() > 32)
27             {
28                 cout<<"ERROR"<<endl;
29                 break;
30             }
31             double r = f*2;
32             if(r >= 1)
33             {
34                 s += '1';
35                 f = r-1;
36             }
37             else
38             {
39                 s += '0';
40                 f = r;
41             }
42         }
43         cout<<s<<endl;
44     }
45     return 0;
46 }