Hello,
This is a strange problem and I hope someone has an explanation to it.
When I use scanf() to read floating point numbers, sometimes the last digit is wrong.
Code:
#include <stdio.h>
int main(void)
{
float f=0;
scanf("%f", &f);
printf("%f\n", f);
return 0;
}
Here is example of working executable (note that only certain numbers are mistaken, not all):
Code:
Press ENTER or type command to continue
99.1
99.099998
Press ENTER or type command to continue
89.99
89.989998
Press ENTER or type command to continue
12.88
12.880000
Press ENTER or type command to continue
333.333
333.333008
Press ENTER or type command to continue
1313.1313
1313.131348
Press ENTER or type command to continue
99999.1
99999.101562
If I change float to double (and %f to %lf, respectively) every value is read correctly.
I know in GCC float is 4 bytes, but how much bytes are for the integer part and how much are for the fractional part of the number?
If there is at least 1 byte for the fractional part that gives the precision of about 0.004 that is more than enough for storing the number "99.1" correctly. Apparently even that small number is wrong.