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 asdoubleand returns adouble. Storing the return value in anintas in this case may sometimes result in an erroneous result - due to the rounding that takes place during the implicit conversion toint.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