binary to decimal conversion

i have written code to convert binary to decimal using array but pow(x,i) function takes only double as parameter but i cannot be double as i is index in array , what can i do?? plz help

int main()
{
int n;
cin>>n;
int a[n];
cin>>a[n];
double x;
x=2;
int i;
for( i =0; i<n; i++)
{
int c,d,e,f,a[i];A
d=a[i];
e=pow(x,i);
f=d*e;
int b=0;
b=f+b;
}
cout<<b;

system("pause");
return 0;
)
Did you try compiling this? What error did it give?
There is an overload of pow(double, int). see http://www.cplusplus.com/reference/clibrary/cmath/pow/
Even if there wasn't, type casting is likely to fix things for you.
And when ambiguities arise, you can explicitly cast with pow( double(x), double(i) ) or pow( (double)x, (double)i ).
Last edited on
here is a big hint...
1 0 0 1 0(binary) = 18 (decimal)

OR

0*1 + 1*2 + 0*4 + 0*8 +1*16 = 18

OR

0*(2^0) + 1*(2^1) + 0*(2^2) + 0*(2^4) + 1*(2^5) = 18

that help you?
Problems with your code. ( I hadn't read it the last time I posted )

int a[n]; you can only declare arrays with constant size. Either change this to int * a = new int[n]; or int a[32];//maximum allowed digits

cin>>a[n]; will not fill the array with values. It will read (n+1)th element in a (which actually doesn't exist). Use a loop. If you chose int a[32] from the last paragraph, for debugging you can omit input and initialize a where you declare it. Example : int a[32] = {0, 1, 0, 0, 1};. Notice that the way you have your code, binary digits have to be in reverse order to produce correct result.

int c,d,e,f,a[i];A. You can't declare a[i]. That would mean declaring a new array. You can use a[i] without declaring it. What is that A? You don't use it. Also it is after the ;.

int b=0; b=f+b; This sets b = f and then does nothing with it. If you want b to be the decimal result, declare it before the for loop.

You don't need all those variables. You could write b = b+pow(2.0,i)*a[i];.
Last edited on
Topic archived. No new replies allowed.