Printf width specifier to maintain precision of floating-point value

后端 未结 8 1363
萌比男神i
萌比男神i 2020-11-21 13:39

Is there a printf width specifier which can be applied to a floating point specifier that would automatically format the output to the necessary number of s

8条回答
  •  死守一世寂寞
    2020-11-21 13:46

    No, there is no such printf width specifier to print floating-point with maximum precision. Let me explain why.

    The maximum precision of float and double is variable, and dependent on the actual value of the float or double.

    Recall float and double are stored in sign.exponent.mantissa format. This means that there are many more bits used for the fractional component for small numbers than for big numbers.

    enter image description here

    For example, float can easily distinguish between 0.0 and 0.1.

    float r = 0;
    printf( "%.6f\n", r ) ; // 0.000000
    r+=0.1 ;
    printf( "%.6f\n", r ) ; // 0.100000
    

    But float has no idea of the difference between 1e27 and 1e27 + 0.1.

    r = 1e27;
    printf( "%.6f\n", r ) ; // 999999988484154753734934528.000000
    r+=0.1 ;
    printf( "%.6f\n", r ) ; // still 999999988484154753734934528.000000
    

    This is because all the precision (which is limited by the number of mantissa bits) is used up for the large part of the number, left of the decimal.

    The %.f modifier just says how many decimal values you want to print from the float number as far as formatting goes. The fact that the accuracy available depends on the size of the number is up to you as the programmer to handle. printf can't/doesn't handle that for you.

提交回复
热议问题