【问题标题】:C printf function specifierC printf 函数说明符
【发布时间】:2012-03-14 05:50:30
【问题描述】:

我需要打印一个 16 位有效数字的浮点值。

现在当我打印时,它会打印出来

即 2.555556

当我希望它打印出来时:2.555555555555556 /// 一共 16 位

我的 printf 说明符目前是:“%20.18lf”

想法?

【问题讨论】:

  • 你知道浮点数没有 16 位精度吗?
  • 我试过“%.16f”,它对数字 1.0 / 3.0 工作得很好。
  • @Tibi:表达式1.0 / 3.0 的类型为double。

标签: c printf specifier


【解决方案1】:

C float 或 double 不够精确,基本上你需要一个高精度的除法函数。这是我写的。它用于整数除法。您可能需要修改它以进行浮点除法。

int dividend=121, divisor=9;
int quotient,remainder;

//first print out the number before decimal point
quotient=dividend/divisor;
printf("%d", quotient);
remainder=dividend-quotient*divisor;

//print out decimal point
printf(".");

int digit_num=20;//this can be any precision you want

//second we calculate the number after decimal point
for(int i=0;i<digit_num;i++)
{
    remainder=remainder*10;
    quotient=remainder/divisor;
    remainder=remainder-quotient*divisor;
    printf("%d", quotient );
    dividend=remainder;
}

printf("\n");

printf("%d digits after decimal point has been printed out\n", digit_num );

【讨论】:

    【解决方案2】:

    以下代码运行良好(您必须启用 C99,因为 %lf 说明符不是早期标准的一部分):

    #include <stdio.h>
    
    int main(void)
    {
            volatile float v = 2.555555555555556;
            printf("%20.18lf\n", v);
            return 0;
    }
    

    打印以下内容:

    $ gcc -std=c99 -Wall -pedantic -o test ./test.c 
    $ ./test 
    2.555555582046508789
    $ 
    

    如果值更短,比如 2.5,它会用零填充它 - 2.500000000000000000。

    所以你在其他地方有错误。通常,您必须发布一个重现问题的最小自洽代码示例。否则你就靠自己了。

    【讨论】:

    • 我找到了问题的人。当我输入时,我也在输入中使用相同的说明符,所以它会崩溃
    【解决方案3】:

    如果该值的类型为float,则小数点后的有效数字可能不会超过 7 位。如果它是double 类型,您可以获得大约15 个。根据系统,long double 可能不会比double 更精确;就我而言,我得到了小数点后大约 17 位有效数字。

    大多数浮点代码使用类型double; float 的精确度要低得多,而且通常不会明显更快。

    我有点惊讶你得到的是2.555556,而不是像2.555555582046508789 这样的"%20.18lf" 格式。

    顺便说一句,l(小写 L)不是必需的。 double 的格式为 "%f",printf 的参数float 提升为double,因此"%f" 对于float 和double 都是正确的。 long double 的格式为 "%Lf"。

    这是我写的一个测试程序:

    #include <stdio.h>
    int main(void) {
        const float f        = 23.0/9.0;
        const double d       = 23.0/9.0;
        const long double ld = 23.0L/9.0L;
        printf("%20.18f\n%20.18f\n%20.18Lf\n", f, d, ld);
        return 0;
    }
    

    以及我在系统上得到的输出:

    2.555555582046508789
    2.555555555555555358
    2.555555555555555556
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-23
      • 2014-01-07
      • 1970-01-01
      • 2013-07-22
      • 2017-11-16
      • 1970-01-01
      相关资源
      最近更新 更多