如何计算转换规范%.*f的精度以保持浮点值的精度?

问题描述 投票:0回答:1

注意:这个问题源自this答案。

如何计算转换规范的精度

%.*f
以保持浮点值的精度?

注意:这里的“保持精度”是指读回打印值后(例如

strtod
scanf
),结果值与原始值相等(NaN除外)。

c floating-point printf precision
1个回答
0
投票

一个简单的解决方案是先通过 x 槽

sprintf
,然后通过
strtod
(产生 y),直到 x = y:

#include <float.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define PREC_MAX 256

void print_f(double x, bool newline)
{
    double y;
    char s[PREC_MAX * 3]; // what is the precise multiplier ?
    bool f_printed = false;

    for (int prec = 1; prec < PREC_MAX; ++prec)
    {
        if (sprintf(s, "%.*f", prec, x) > 1) // may encoding error occur ?
        {
            y = strtod(s, 0); // is there a real need of error handling ?
            if (x == y)
            {
                printf("%s", s);
                f_printed = true;
                break;
            }
        }
    }
    if (!f_printed)
    {
        printf("%.*g\n", DBL_DECIMAL_DIG, x); 
    }
    if (newline)
    {
        printf("\n");
    }
}

int main(void)
{
    print_f(0.000000000000000000000001617, true);   // 0.000000000000000000000001617
    print_f(1.0, true);                             // 1.0
    print_f(0x1p-27, true);                         // 0.000000007450580596923828
}
© www.soinside.com 2019 - 2024. All rights reserved.