I have read that floating numbers are stored as per IEEE 754 representation and sometimes approximate value is displayed if its not possible to represent the number.
I have written the following code in which i am extracting fractional part then multiplying it by 10 nine times inside the loop. At the end of the loop the value is 142000000.000000 (variable g). I multiplied it again with 10 outside the loop and got the result as 1419999999.999999.
I stored the value which was calculated inside for loop explicitly in another variable(k) and multiplied it with 10 and got the result as 1420000000.000000
Can you please tell me why the difference how it is able to store the value correctly in the second instance (In variable k).
#include<stdio.h>
#include<math.h>
int main()
{
double f=3.142,g,i;
int j;
g=modf(f,&i);
printf("Inside loop");
for(j=1;j<=9;j++)
{
g = g * 10.0;
printf("\n%lf",g);
}
printf("\nLoop ends");
g = g * 10.0;
printf("\nThe value of g is %lf",g);
double k = 142000000.000000;
k = k * 10.0;
printf("\nThe value of k is %lf",k);
}
Output
Inside loop
1.420000
14.200000
142.000000
1420.000000
14200.000000
142000.000000
1420000.000000
14200000.000000
142000000.000000
Loop ends
The value of g is 1419999999.999999
The value of k is 1420000000.000000