C++浮動小数点数回転文字列の精度問題

1734 ワード

C++の浮動小数点数回転文字列が呼び出されます_gcvt_sまたは_ecvt_sまたは_fcvt_s
関数についてgcvt_sにとって
errno_t _gcvt_s( 
   char *buffer,
   size_t sizeInBytes,
   double value,
   int digits 
);
template 
errno_t _gcvt_s( 
   char (&buffer)[cchStr],
   double value,
   int digits 
); // C++ only

パラメータdigitsはフォーマットされた桁数(小数点前後を含む)を表します.
浮動小数点数は不正確な表現なので、桁数を指定する必要があります.
char txt[1024]; auto err = _gcvt_s(txt, 3.1415926, 1000);
txtの値は「3.1415926」ではなく「3.141592600000006840537025709636509418487548828125」(Win 7 x 64,VS 2015,VC++v 140)
printf("%f",3.1415926)のデフォルトインプリメンテーションを参照して、digitsを6に指定します(エラー:%nfは小数点以下のnビットを保持し、浮動小数点数全体の桁数ではありません)
MSVCライブラリソースファイルX:Program Files(x 86)Windows Kits10Source10.0.10240.0\ucrt\inc\corecrt_internal_stdio_output.h line: 2324
           //The default precision depends on the format specifier used.  For            //%e, %f, and %g, C specifies that the default precision is 6.  For            //%a, C specifies that "if the precision is missing and FLT_RADIX            //is a power of 2, then the precision is sufficient for an exact            //representation of the value"(C11 7.21.6.1/8).            //           //The 64-bit double has 53 bits of precision.  When printing in            //hexadecimal form, we print one bit of precision to the left of the            //radix point and the remaining 52 bits of precision to the right.            //Thus, the default precision is 13 (13 * 4 == 52).             if (_format_char == 'a' || _format_char == 'A')             {                 _precision = 13;             }             else             {                 _precision = 6;             }