Created
July 29, 2014 04:04
-
-
Save ivycheung1208/49aee9c2f58e46b4c38a to your computer and use it in GitHub Desktop.
CC150 5.2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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