#include <stdio.h>
#include <stdlib.h>
int main() {
float n;
scanf("%f", &n);
printf("%.3f", n);
}
input: 51444.325061
my output: 51444.324
expected output: 51444.325
why does I dont get the proper answer?
#include <stdio.h>
#include <stdlib.h>
int main() {
float n;
scanf("%f", &n);
printf("%.3f", n);
}
input: 51444.325061
my output: 51444.324
expected output: 51444.325
why does I dont get the proper answer?
32-bit float
can encode about 232 different values.
51444.325061
is not one of them**. Instead the nearest float
is exactly 51444.32421875. The next best choice would be 51444.328125.
Printing 51444.32421875 to 3 decimal places is best as "51444.324".
why does I dont get the proper answer?
float
is too imprecise to encode 51444.325061 as OP desires. Using double
will help. The same problem exists, yet only appears when about 16+ significant digits are needed.
** Encodable finite values are of the form: some_integer * 2some_exponent.
Internally, floating-point numbers are not represented as decimal fractions, as you might expect. Instead, they use a floating-point representation based on binary (base-2) numbers.
Because they're base-2, these floating-point numbers cannot represent decimal fractions exactly.
Here are the available float
values nearest to 51444.325061, along with their exact decimal equivalents:
0x4748f452 51444.32031250 0.784978032112121582031250 × 2^16
0x4748f453 51444.32421875 0.784978091716766357421875 × 2^16
0x4748f454 51444.32812500 0.784978151321411132812500 × 2^16
0x4748f455 51444.33203125 0.784978210926055908203125 × 2^16
So you can take your pick between 51444.324 or 51444.328. But obviously 51444.324 is closer.