I am not able to convert from decimal to binary in C.Everytime I get a output which is one less than the desired output.For ex.:5 should be 101 but shows up as 100 or 4 should be 100 but shows up as 99.
#include<stdio.h>
#include<math.h>
void main() {
int a,b=0;
int n;
printf("Enter a Decimal Number\n");
scanf("%d",&n);
for(int i=0;n>0;i++) {
a=n%2;
n=n/2;
b=b+(pow(10,i)*a);
}
printf("%d",b);
}
My output is always one less than the correct answer and I dont know why.It fixes the problem if take b as 1 instead of 0 in the beginning but i dont know why.Please Help.I have just started C a few days ago.
powfor integer math is usually a bad sign.b = d;suffices. (More to the point,dwas binary already, if it has a meaningful base at all.) If you want to construct the binary representation of an integer, don't construct it in an integer. You want it as a string. The first decimal number I tried your code on was 1234, and it converted it to -2147483648, which is not the correct binary representation.