-1

I am new to programming and I've been practising C++ in VS Code with Coderunner and Microsoft C/C++ extensions enabled. I wrote this code to convert decimal numbers to binary numbers.

#include <iostream>
#include <math.h>
using namespace std;

int main()
{
    int d;
    int c = 0;
    cout << "Enter a decimal number : ";
    cin >> d;
    for(int i=0; d!=0; i++)
    {
        c += pow(10,i)*(d%2);
        d = d/2;
    }
    cout << "Binary value : " << c;
}

But it is giving me wrong results. For e.g. upon giving 5 as input the output is 100 while it should be 101. I've also run this same code on other compilers including online compilers and it's working fine. Also by replacing int c with float c it is working fine in VS Code too. But I don't understand why it is not working with int c as the logic is correct. If anyone can explain me I would be really thankful.

  • [`std::bitset`](https://en.cppreference.com/w/cpp/utility/bitset) – 463035818_is_not_an_ai Jul 22 '23 at 09:25
  • You must include `` in place of the `` of the C code. The `pow` function on an `int` gives different result in C depending on the compiler library. Note that `pow()` to have an `int` may give false results, all compilers gives false results but for some that appears for different values. – dalfaB Jul 22 '23 at 09:48

1 Answers1

1

pow is a floating point operation and is not guaranteed to give exact results for integers. So you cannot be sure that (for example) pow(10, 3) equals 1000, it might equal 999.99999999 and this means that your code is incorrect. Don't use pow with integers if you are expecting exact results.

One way to fix your code would be to add a rounding operation like this c += round(pow(10,i))*(d%2);. But really you should not be using pow with integers. A much better way to write this code is to declare c as a std::string, just add '0' or '1' to the string for each binary digit. Like this

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int main()
{
    int d;
    string c;
    cout << "Enter a decimal number : ";
    cin >> d;
    while (d != 0)
    {
        c += d%2 ? '1': '0'; // add a binary digit to the string
        d = d/2;
    }
    reverse(c.begin(), c.end()); // reverse the digits of the string
    cout << "Binary value : " << c;
}

This code has the advantage of not using pow. It also works with a much bigger range of values. Your version would suffer from integer overflow because you are trying to store binary digits in an int which has a limited range (unlike a string).

There are still some problems with this code, it doesn't work with negative numbers and it doesn't work with zero. But I'll leave you to make those improvements.

john
  • 85,011
  • 4
  • 57
  • 81