The code is giving false answers. İf number equals 42, it turns it to 101010. Ok, it is true. But if number equals 4, it turns it to 99. I didn’t find the mistake. How can i fix the code?
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int i,digit,number=4;
long long bin= 0LL;
i=0;
while(number>0)
{
digit=number%2;
bin+=digit*(int)pow(10,i);
number/=2;
i++;
}
printf("%d ",bin);
getch();
}
Stop using floating point calculations for this. You are subject to the vagaries of floating point. When I ran your program with my compiler, the output was 100. But I guess your compiler treated the floating point
powdifferently.A simple change to make the code behave, and use integer arithmetic only, would be like this:
But I’d rather see the binary built up in a string rather than an integer.