简体   繁体   English

C变量函数va_arg返回错误的双精度

[英]C variadic functions va_arg returns wrong double precision

So I'm nearly done reimplementing printf(3) (I can't use any function that would the conversion for me) in C . 所以我几乎做了重新实现printf(3)我不能使用任何功能会为我的转化)的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 . 现在我已经实现了所有的转换,我看到了一些奇怪的东西,当我通过我的函数一个double使用说%g100.10然后va_arg给我100.09999999999999所以当然我的转换然后给我一个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 . 认为知道这个值是错误的,因为当我逐步完成程序时,我看到double d = 100.09999999999999

Should I do it differently ? 我应该采用不同的方式吗? Because the real printf seems to be getting the correct value. 因为真正的printf似乎得到了正确的值。

EDIT: 编辑:

printf("%#.10g\n", testd); #=> 100.1000000000

Is this due to rounding or that maybe the real printf is getting the good value ? 这是因为四舍五入还是真正的printf可能获得了良好的价值?

Just add format specifier, and printf will perhaps show the same issue: 只需添加格式说明符, printf可能会显示相同的问题:

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. 原因是在我们的例子中,数字100.1 (大多数数字)没有精确的二进制表示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM