Skip to content

Instantly share code, notes, and snippets.

@ThunderXu
Created March 24, 2013 07:40
Show Gist options
  • Save ThunderXu/5230924 to your computer and use it in GitHub Desktop.
Save ThunderXu/5230924 to your computer and use it in GitHub Desktop.
Given a real number between 0 and 1 (e.g., 0.72) that is passed in as a double, print the binary representation. If the number cannot be represented accurately in binary with at most 32 characters, print "ERROR."
#include <iostream>
#include <string>
std::string PrintBinary(float);
int main()
{
std::cout<<PrintBinary(0.81256)<<std::endl;
}
std::string PrintBinary(float num)
{
if(num>=1||num<0)
{
return "ERROR";
}
if(num==0)
{
return 0;
}
std::string result = "0.";
int count=0;
while(num!=0)
{
count++;
num=num*2;
if(num>=1)
{
result=result+"1";
num-=1;
}
else
{
result=result+"0";
}
if(count>32)
{
return "ERROR";
}
}
return result;
}
@pranuarjun
Copy link

this will always go to the ERROR

@alibeigi
Copy link

Your code is fine. However, it always returns Error. Based on my checking, in the editor which I am using (.Net 2012) the value which is assigned to num is slightly different from the one that I have set. For example, I have set num to 0.4 but its real value is 0.400000006 which cause the program to return ERROR.
you can see the exact value of the num by printing it with a high precision using this command:
cout << setprecision(10) << d; // #include

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment