【问题标题】:Floating point formatting till specified number浮点格式直到指定数字
【发布时间】:2014-05-26 17:59:00
【问题描述】:

以下是一个示例程序

#include<stdio.h>
#include<math.h>
main()
{
        int x;
        scanf("%d",&x);
        printf("%.2f\n",(1/pow(2,x)));
}

这里我给出 .2f 用于浮点格式。我们也可以根据需要分别给出 .3f 或 .5f 等。

假设我们直到 '.' 后面的小数点后才知道。它要被打印出来。我想通过输入给出一个值 n 之类的东西,以便它打印小数直到 n。

像 .nf 如果 n = 5 和 x =1,它会打印 0.50000,对于 n = 3,它应该打印 0.500

我如何做到这一点?

【问题讨论】:

    标签: c floating-point printf


    【解决方案1】:

    您可以将所需的精度指定为变量:

    int n = 5;
    printf("%.*f\n", n, (1.0/pow(2,x)));   /* equivalent to %.5f */
    

    引用man 3 printf:

       An  optional  precision,  in the form of a period ('.')  followed by an
       optional decimal digit string.  Instead of a decimal digit  string  one
       may write "*" or "*m$" (for some decimal integer m) to specify that the
       precision is given in the next  argument,  or  in  the  m-th  argument,
       respectively,  which must be of type int.
    

    【讨论】:

      猜你喜欢
      • 2010-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-25
      • 2010-12-16
      相关资源
      最近更新 更多