Skip to content

Instantly share code, notes, and snippets.

@ivycheung1208
Created July 29, 2014 04:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivycheung1208/49aee9c2f58e46b4c38a to your computer and use it in GitHub Desktop.
Save ivycheung1208/49aee9c2f58e46b4c38a to your computer and use it in GitHub Desktop.
CC150 5.2
/* CC150 5.2
* Given a real number between 0 and 7 (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 <vector>
using namespace std;
bool real2bin(double d, vector<int> &bin)
{
if (d >= 1 || d <= 0)
return false;
int bitCount = 0; // can use bin.size() instead
while (d != 0 && ++bitCount <= 32) {
bin.push_back(d >= 0.5);
d = (d >= 0.5) ? d * 2 - 1 : d * 2;
}
if (d == 0) return true;
else return false;
}
int main()
{
double d;
cin >> d;
vector<int> bin;
if (!real2bin(d, bin)) {
cout << "ERROR!" << endl;
// for (auto i : bin)
// cout << i;
// cout << endl;
}
else {
for (auto i : bin)
cout << i;
cout << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment