So I'm nearly done reimplementing printf(3)
(I can't use any function that would the conversion for me) in C
.
Now that I have implemented all the conversions I'm seeing something weird, when I pass my function a double
to use with say %g
like 100.10
then va_arg
gives me 100.09999999999999
so of course my conversion then gives me a string with 100.099999
.
I fetch the double like this:
double d = (double)(va_arg(args, double));
And I am calling both functions like this:
double testd = 100.10;
my_printf("%g", testd); #=> 100.099999
printf("%g", testd); #=> 100.1
I think that I know that the value is wrong because while stepping through the program I'm seeing that double d = 100.09999999999999
.
Should I do it differently ? Because the real printf seems to be getting the correct value.
EDIT:
printf("%#.10g\n", testd); #=> 100.1000000000
Is this due to rounding or that maybe the real printf
is getting the good value ?
Just add format specifier, and printf
will perhaps show the same issue:
printf("%0.20g\n", d); // 100.09999999999999 on my system
The reason is that in our case the number 100.1
(as most of all numbers) does not have exact binary representation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.