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
*/
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;
}