1

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
*/
JaMiT
  • 14,422
  • 4
  • 15
  • 31
Goshawk
  • 13
  • 3
  • 4
    Any program that calls `pow()` with two integers is automatically broken by default. This is not what `pow()` is for. – Sam Varshavchik Jan 16 '23 at 02:00
  • Please do not copy/paste the same text to bypass the minimum length requirement. Doing so is a violation of the site guidelines, and an insult to everyone here that you're asking for help. – Ken White Jan 16 '23 at 02:05
  • @KenWhite, I am sorry. I honestly did not do it to bypass it. I am actually a new user and hence I am unaware of many aspects if not all of them work in here. I tried to follow the indications in the best of my abilities as for now. – Goshawk Jan 16 '23 at 02:20
  • @KenWhite When I wrote the question I had saw three sections: "Title", "Body", "What I/you tried" or something on that like or with a similar meaning. since I what I have tried was the same thing as the body. I wrote it in that section too, in the hope that people would understand what I wrote. You can clearly see that I wrote the same thing twice, why would I want to bypass the word limit? I was more like a chore to do so. I did it cause I thought I had to put that in the last section as well. Thanks for editing out my code, but the sarcastic tone and the accusations are uncalled for. – Goshawk Jan 16 '23 at 02:44
  • @Goshawk *"since I what I have tried was the same thing as the body."* -- this is one place you went off the intent. Perhaps a more accurate description of the intended use of these sections would be "Title", "Textual description", and "Code demonstrating the textual description". There is supposed to be no overlap (I think -- I have not seen the exact screen you did, but what I describe matches what is recommended in [ask]). – JaMiT Jan 16 '23 at 06:48
  • I tried your code (after changing `int n;` to `int n = 13;` and commenting out `cout<<"Enter decimal number: ";` and `cin>>n;`) and the output was `1101`. You are probably running afoul of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) manifesting as one of your `pow` invocations returning a value a little smaller than the expected integer. Could you try writing your own power function to see if it makes a difference? – JaMiT Jan 16 '23 at 06:55

2 Answers2

1

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

Something Something
  • 3,999
  • 1
  • 6
  • 21
  • 1
    You add `’0’` to a number between 0 and 9 to convert to the corresponding character code. The character encoding is usually ASCII these days, but it doesn’t have to be. Regardless of the encoding, adding `’0’` Is required to work. – Pete Becker Jan 16 '23 at 04:01
  • *"Pass parameters through the command line, not `std::cin`"* -- why? – JaMiT Jan 16 '23 at 07:02
  • You listed five issues with the code in the question. However, numbers 3 and 4 are not issues in the question's code -- they are issues that arise when you attempt to implement number 2. – JaMiT Jan 16 '23 at 07:10
1

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;
}
subasri_
  • 100
  • 6
  • @subasri_ Thank you a lot for the help. It was easy and very clear for me. May you have a blessed day. – Goshawk Jan 16 '23 at 17:05