Pls, help with this problem. I need to count the number of digits after the decimal point. But when f should be 0 it becomes 1 and i becomes 2 (but should be 3). After the code, the output from the console
#include <math.h>
#include <stdio.h>
int main()
{
double i;
double f;
int count = 0;
double eps = 10.123;
while(f!=0){
f = modf(eps, &i);
printf("%f \n%f\n", i, f);
count = count + 1;
i=0;
eps=f*10;
printf("%f\n\n", eps);
}
printf("Count = %d", count);
return 0;
}
10.000000 0.123000 1.230000
1.000000 0.230000 2.300000
2.000000 0.300000 3.000000
2.000000 1.000000 10.000000
9.000000 1.000000 10.000000
9.000000 1.000000 10.000000
9.000000 1.000000 10.000000
9.000000 1.000000 10.000000
9.000000 1.000000 9.999999
9.000000 0.999999 9.999993
9.000000 0.999993 9.999933
9.000000 0.999933 9.999332
9.000000 0.999332 9.993321
9.000000 0.993321 9.933209
9.000000 0.933209 9.332090
9.000000 0.332090 3.320898
3.000000 0.320898 3.208983
3.000000 0.208983 2.089828
2.000000 0.089828 0.898284
0.000000 0.898284 8.982839
8.000000 0.982839 9.828386
9.000000 0.828386 8.283855
8.000000 0.283855 2.838551
2.000000 0.838551 8.385506
8.000000 0.385506 3.855058
3.000000 0.855058 8.550583
8.000000 0.550583 5.505825
5.000000 0.505825 5.058253
5.000000 0.058253 0.582528
0.000000 0.582528 5.825281
5.000000 0.825281 8.252811
8.000000 0.252811 2.528114
2.000000 0.528114 5.281143
5.000000 0.281143 2.811432
2.000000 0.811432 8.114319
8.000000 0.114319 1.143188
1.000000 0.143188 1.431885
1.000000 0.431885 4.318848
4.000000 0.318848 3.188477
3.000000 0.188477 1.884766
1.000000 0.884766 8.847656
8.000000 0.847656 8.476562
8.000000 0.476562 4.765625
4.000000 0.765625 7.656250
7.000000 0.656250 6.562500
6.000000 0.562500 5.625000
5.000000 0.625000 6.250000
6.000000 0.250000 2.500000
2.000000 0.500000 5.000000
5.000000 0.000000 0.000000
Count = 50
Just because you assigned 10.123
to the variable does not mean that is exactly what got stored there.
Floating point representations are only approximate (although they do have very high precision)
10.123
cannot be precisely stored, and the binary approximation is 10.1229999999...
, as shown by this code.
#include <stdio.h>
int main(void) {
double x = 10.123;
printf("%3.3f is stored as %3.20f\n", x, x);
return 0;
}
10.123 is stored as 10.12299999999999933209