#include<iostream>
#include<cmath>
using namespace std;
int binary_conversion(int e,int w,int q,int n,int i)
{
while(abs(w)>=1){//abs(e) to ensure that for negative numbers
if(abs(w)>=1){
e=w%2;
w=w/2;
}
else
{
w=0;
}cout<<"i is"<<i<<"\n";cout<<"q is before"<<q<<"\n";
int r=pow(10,i);cout<<" r is"<<r;
q=q+pow(10,i)*e;cout<<"q is"<<q<<"\n";
i++;
} return q ;
}
int main(){
int n,w,q=0;int i=0,e;
cin>>n;w=n;e=n;
binary_conversion(e,w,q,n,i);
cout<<q;
}
This program converts an integer to a binary digit. The error that I'm getting in this program is it's not giving 10^i value correctly. The line from where it's not giving the desired output is
q=q+pow(10,i)*e;cout<<"q is"<<q<<"\n";
the value of i in the 3rd iteration is 2 and 10^i should be 100, but it's 99.
Any suggestion would be appreciated.
Your expression
10^ican be expressed iteratively:The above code does not involve floating point so there will be no loss from conversions.
You may want to change your expression evaluation to an iterative method.