0

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%'

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by jagan605
0

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.

Edited by jonsca: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.