C Tutorial/printf scanf/printf Precision

Материал из C\C++ эксперт
Перейти к: навигация, поиск

For floating arguments, precision indicates how many digits are printed after decimal points.

#include <stdio.h>
main()
{
    printf("%10.4e\n", 35.99999);
}
3.6000e+01

Precision

Precision indicates the minimum number of digits printed for type integers d, i, o, u, x, and X.


#include <stdio.h>
main()
{
    printf("%10.4d\n", 35);
}
0035
  1. 10 is the field-width.
  2. 4 is the precision.

Using precision while printing integers, floating-point numbers, and strings

#include <stdio.h>
int main()
{ 
   int i = 873;
   double f = 123.94536;        
   char s[] = "Happy Birthday"; 
   printf( "Using precision for integers\n" );
   printf( "\t%.4d\n\t%.9d\n\n", i, i );
   printf( "Using precision for floating-point numbers\n" );
   printf( "\t%.3f\n\t%.3e\n\t%.3g\n\n", f, f, f );  
   
   printf( "Using precision for strings\n" );
   printf( "\t%.11s\n", s );
   return 0;
}
Using precision for integers
        0873
        000000873
Using precision for floating-point numbers
        123.945
        1.239e+02
        124
Using precision for strings
        Happy Birth