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.
powis a floating-point function; it takes adoubleargument and returns adoublevalue. In the C implementation you are using,powis badly implemented. It does not always produce a correct result even when the correct result is exactly representable. Stop using it for integer arithmetic.Rewrite the code to compute the desired power of ten using integer arithmetic.
Also, do not compute binary numerals by encoding them a decimal within a
inttype. It is wasteful and quickly runs into bounds of the type. Use either bits within anunsignedtype or an array ofchar. Whenscanf("%d",&n);executes, it converts the input string into binary and stores that inn. Sonis already binary; you do not need to decode it. Use a loop to find its highest set bit. Then use another loop to print each bit from that position down to the least significant bit.