You're problem is that you're using float when you should be using int and you haven't initialized any of your variables. Change float
to int
and initialize your variables to 0
and your code will work.
The reason your code isn't working is because sum
isn't initialized. When you use sum = sum + t * pow (2, i)
, you are adding an arbitrary number to the result in the first go around. sum
could be anything before it's initialized (ie -1241232
).
Even though the only variables that really need to be initialized are sum
, d
, and i
, it's a good practice to initialize them anyway (better safe than sorry). In fact, initialized variables are a very common cause of errors. Initialize everything.
The floating point datatype is also causing problems in you code, in the second loop. When the user inputs a floating point number, like 110.1101, it gets approximated to another number (ie 110.110098) - this has to do with the limitation of the floating point datatype.
In your second loop, with the input approximated to 110.1100998, the problem is caused in this statement:
sum = sum + x * pow (2.0f, -i);
Because x isn't 1
or 0
throughout the whole loop (sometimes 9
or 8
, etc). What's more, the loop doesn't just iterate 4 times (1101), it does many more. This is because of this statement:
d = d * 10;
When d
gets multiplied by 10
, it goes from 0.100998
to about 1.00979
- not 1.00998
like you'd expect. These two discrepancies are what's causing your results to be erroneous when you input values more precise than a single digit.
Finally, here's some working code:
#include <stdio.h>
#include <math.h>
int main (){
int p = 0, i = 0, j = 0, t = 0, x = 0;
float n = 0.0f, sum = 0.0f, d = 0.0f;
printf("enter the binary number: ");
scanf("%f", &n);
p = n;
d = n - p;
while (p > 0){ // never use the float datatype for iteration
t = p % 10;
sum = sum + t * pow (2.0f,i);
p = p / 10;
i = i + 1;
}
i = 1;
while (d > 0.00001){
d = d * 10;
x = d;
sum = sum + x * pow (2.0f, -i);
d = d - x;
i = i + 1;
}
printf ("decimal value is %f\n", sum);
getchar ();
return 0;
}