pls can u find the error in my program

#include<iostream>
#include<conio.h>
#include<math.h>
using namespace std;
int main()
{
int n,s,a,c,i,b,;

a=0;
c=0;
cout<<"enter the binary number"<<endl;
cin>>n;
cout<<"enter the no of digits in the number"<<endl;
cin>>s;
for(i=0;i<s;i++)
{
for(b=0;b<s;b++)
{

c=c+((n/pow(10,b))%10)*pow(2,b);
}
}
cout<<"the decimal equivalent is:"<<c<<endl;
getch();
return 0;
}
It does not compile
1. You had a comma in your declarations immediately before the semi-colon.
2. Depending on your compiler, you may not have a pow function that accepts 2 ints.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include<iostream>
#include<conio.h> 
using namespace std;

int pow(int num,int exp) // This will work for your purposes.
{
	int out = 1;
	while (exp-- > 0)  out *= num;
	return out;
}

int main()
{
	int n,s,a,c,i,b; // You had a comma before the semi-colon

	a=0;
	c=0;
	cout<<"enter the binary number"<<endl;
	cin>>n;
	cout<<"enter the no of digits in the number"<<endl;
	cin>>s;

	for(i=0;i<s;i++)
	{
		for(b=0;b<s;b++)
		{
			c=c+((n/pow(10,b))%10)*pow(2,b); // If your compiler doesn't have int pow(int,int) supported, you'll need to write one or cast these.
		}
	}
	cout<<"the decimal equivalent is:"<<c<<endl;
	getch();
	return 0;
}


Now it will compile. I'll let you figure out the problems with the algorithm giving you the wrong number.

Hint: I entered 1101 (13) and it converted it to 52 (which is actually 110100)

***SPOILER HINT****
1
2
3
4
5
for (int digit = 0; binary > 0; digit++)
{
	decimal += (binary%10) * pow(2,digit);	// Extract the right-most digit and multiply by the value of this decimal place
	binary /= 10; // Shift the decimal place over
}
Last edited on
thank u
Topic archived. No new replies allowed.