gcc double printf precision - wrong output

允我心安 提交于 2019-12-24 10:54:19

问题


#include <stdio.h>
#include <wchar.h> 
int main()
{
    double f = 1717.1800000000001;
    wprintf(L"double      %.20G\n", f);
    return 0;
}

outputs (and expected below):

double      1717.1800000000000637
double      1717.1800000000001

This is on Ubuntu 11.10 x64 (but also when compiling for 32 bit).

The problem that I try to solve, is that on Windows it outputs the number exactly like in code, and I need to make low-level formatting (swprintf) to work like in Windows, for portability issues.


回答1:


1717.1800000000001 is not exactly representable as double, so you only get a value near to it in f. The value stored in f is exactly 1717.180000000000063664629124104976654052734375.

The problem is now that windows does only output 17 significant digits, although 20 were requested (which is a known bug, AFAIK it's somewhere in their bug database).

If you can't limit the field length to a sane value (like "%.17G"), you need a wrapper to mimic this bug.




回答2:


wprintf function is implemented by standard C library, not by gcc.

Number 1717.1800000000001 has 13 digits after the floating point. However, it doesn't have exact representation in 64-bit binary floating point format.

Format "%.20G" requires outputting 20 significant digits which is the count of digits in 1717.1800000000000637. Hence this output is what expected. Either Windows standard C library treats the format differently or makes incorrect rounding.

On the other hand, you can require a specific number of digits after the floating point by using "%f" format, e.g. "%.13f" rounds the output to exactly 13 digits after the floating point an it prints 1717.1800000000001 as expected.




回答3:


Well, your expected output conflicts with your format string. "%.20G" means you want 20 significant digits, and that's what you're getting. If you want 17 significant digits, as your expected output has, use "%.17G".




回答4:


double f = 1717.1800000000001;

This line of code cannot be executed accurately. The constant has 17 decimal digits of precision, a double has 15.9.



来源:https://stackoverflow.com/questions/9496396/gcc-double-printf-precision-wrong-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!