i recently started typing the code for the program to convert a binary number to its decimal form and i got stuck when my compiler reported this error.

this is what i have typed till now.

#include<iostream>
using namespace std;
#include<math.h>
main()
{
 int n,s=0,k=0,a,b,c;
 cout<<"\n\n\tPROGRAM TO CONVERT BINARY TO DECIMAL";
 cout<<"\ngive number: ";
 cin>>n;
 b=n;
 while(n!=0)
 {
  n=n/10;
  s+=1;
 }
 for(int i=s;i>+1;i--)
 {
  a=b%(pow(10,s-1));
  c=pow(2,s-i);
  k=k+c;
 }
 cout<<k<<"\n";
 return 0;
}

error:invalid operands of typed 'int' and 'double' to binary 'operator%'

Recommended Answers

All 2 Replies

I'm surprised it didn't give you grief for pow, as there is no definition that takes 2 ints (http://www.cplusplus.com/reference/clibrary/cmath/pow/)

Look into fmod (http://www.cplusplus.com/reference/clibrary/cmath/fmod/) which is like % but for floats/doubles/etc.

Also, you should include <cmath> instead of math.h and main() should return an int.

I ran the program but I did not check your logic completely. I think you are off by one exponent. Rather than go through all this exponentiation you should look into the >> and << (shift operators for bits, not the operator for iostream).

EDIT: Do a quick search around the site. There are a ton of examples. Most of them take in the binary as a string (which I was going to suggest) and then do the bitshifting.

i have not yet learnt how to use strings .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.