Home > Mobile >  Why isn't this decimal to binary code not working? I did not want to use arrays or strings
Why isn't this decimal to binary code not working? I did not want to use arrays or strings

Time:01-16

I wrote this code and the output does not match the predicted one. In this case, I took as input n=13
Output I want: 1101
Output I get: 1100

#include <iostream>
#include <cmath>

using namespace std;

int main(){

    int n; //n is the decimal number.
    
    cout<<"Enter decimal number: ";
    cin>>n;
    
    int binary = 0;
    int i = 0;
    
    while(n != 0){
        binary = binary   pow(10, i) * (n % 2);
        n = n/2;
        i  ;
    }
    
    cout<<"Equivalent binary is: "<< binary;

}
/* tracing binary = 0, 1, 1, 101, 1101
i = 0, 1, 2, 3, 4
n = 13, 6, 3, 1, 0
*/

CodePudding user response:

A few issues with your code:

  1. (not a bug) Pass parameters through the command line, not std::cin

  2. As it is binary, accumulate on a string, not on an integer as the maximum number of characters is 32 chars while an int will only have 20 digits available.

  3. For transforming the binary digit into an ascii digit, just add the binary digit (0 or 1) to the characters zero ('0').

  4. Make a do loop instead of a while loop to tackle the edge case where n is zero.

  5. (not a bug) Avoid using namespace std; if possible

The result code would be like this:

#include <iostream>

int main( int argc, char* argv[] )
{
    if ( argc<= 1 ) {
        std::cout << "Usage: prog <number> " << std::endl;
        return 0;
    }
    int n = atoi( argv[1] );
    
    std::string binary;
    do {
        char ch = '0'   (n % 2);
        binary = ch   binary;
        n = n/2;
    } while ( n!= 0 );
    std::cout<<"Equivalent binary is: " << binary << std::endl;
}

Example:

$ calcbinary 123
Equivalent binary is: 1111011

Godbolt: https://godbolt.org/z/GjdePM5qE

CodePudding user response:

pow() function takes arguments as double and returns a double. Storing the return value in an int as in this case may sometimes result in an erroneous result - due to the rounding that takes place during the implicit conversion to int.

When I tried executing the code, I observed that when i=2, pow(10, 2) was returning 99. This resulted in the wrong output.

You could try the below snippet for converting decimal to binary without using strings or array and avoiding the usage of pow() function

int binary = 0;
int i = 1;
while(n!=0) {
    binary  = ((n % 2) * i);
    i *= 10;
    n /= 2;
}
  • Related