-
Notifications
You must be signed in to change notification settings - Fork 0
/
5.2.cpp
32 lines (31 loc) · 792 Bytes
/
5.2.cpp
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
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
string print_binary(string val){
int pos = val.find('.', 0);
int intpart = atoi(val.substr(0, pos).c_str());
double decpart = atof(val.substr(pos, val.length()-pos).c_str());
string intstr = "", decstr = "";
while(intpart > 0){
if(intpart&1) intstr = "1" + intstr;
else intstr = "0" + intstr;
intpart >>= 1;
}
while(decpart > 0){
if(decstr.length() > 32) return "ERROR";
decpart *= 2;
if(decpart >= 1){
decstr += "1";
decpart -= 1;
}
else
decstr += "0";
}
return intstr + "." + decstr;
}
int main(){
string val = "19.25";
cout<<print_binary(val)<<endl;
return 0;
}