@capnrap,
I have to admit that I don't think this is a good way of doing the problem. A more common way would be to loop through looking at the end digit (decimal%2) and add character '0' or '1' at the start of a results string, followed by decimal /= 2 . Finally, print out the whole string.
However ... with your existing technique:
(1)
result = 2 ^ power;
doesn't do what you think it does (^ is a bitwise operator; you would need pow())
(2) Your test for looping is wrong - you should test on remaining power, not decimal, as the binary representation might end ...000 and you do need to write those zeroes.
(3) You should write a '1' if decimal/result is non-zero, not if remain >= 1 (which is usually true).
(4) log() and pow() are phenomenally expensive operations when you only need to be multiplying or dividing by 2 (which can, in fact, be accelerated by bitshifting).
(5) Consider using a separate function - you are tying down main() to just doing this single number conversion.
With the caveat that I REALLY DON'T THINK THIS IS A GOOD WAY OF DOING THE PROBLEM, minimal changes to your code are below. Note that it will only work for a number strictly greater than zero.
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
|
/* ***** This is NOT A GOOD WAY OF DOING THE PROBLEM **** */
#include <iostream>
#include <cmath> // you need this header for log() and pow()
using namespace std;
int main() {
int decimal, power, result;
cout << "Enter decimal number:" << endl;
cin >> decimal;
power = log(decimal)/ log(2); // this is clunky ... and may well fail due to floating-point round-off
while (power >= 0) // test on remaining positions, NOT residual number - you may have to write ...000
{
result = pow(2,power); // 2 ^ power does NOT do what you think it does
if ( decimal / result !=0 ) { // correct your test for a non-zero digit
cout << "1";
decimal = decimal - result;
}
else {
cout << "0";
}
power = power - 1;
}
cout << endl;
return 0;
}
|