3.2.2 printf () function
Corresponding to the formatted input function scanf () is the formatted output function printf (), whose function is to output the output items listed in the output item list in the format specified in the control string to the default output device (typically the display), and the basic format is:
printf ("Control string", output Item list)
An output item can be a constant, a variable, an expression, and its type and number must match the type and number of format characters in the control string, separated by commas when there are multiple output items.
The control string must be enclosed in double quotes, consisting of a format description and two parts of a normal character.
1. Format description
The General format is:
%[< modifiers >]< format characters >
The format characters specify the output format of the corresponding output item, as shown in table 3-2 for the common format characters.
As you can see, when the field width is less than the actual width of the data, the integer is output by the actual field width of the number, rounding the number of floating-point numbers, and the corresponding decimal places. For example: 12.34567 press%5.2f output, output 12.35. If the field width is less than the width of the integer portion of the floating-point number, the floating-point number is output by the actual digits, but the decimal digits still follow the value given by the width modifier. As above 12.34567 press%2.1f output, the result is: 12.3.
In practical applications, there is also a more flexible field-wide control method, using the value of a constant or variable as the output field width, the method is a "*" as a modifier, inserted after the%.
For example:
i=123;
printf ("%*d", 5,i);
long int b;
short int c;
unsigned int d;
char e;
float f;
double g;
a=1023;
b=2222;
c=123;
d=1234;
e='x';
f=3.1415926535898;
g=3.1415926535898;
printf("a=%d\n",a);
printf("a=%0\n",a);
printf("a=%x\n",a);
printf("b=%ld\n",b);
printf("c=%d\n",c);
printf("d=%u\n",d);
printf("e=%c\n",e);
printf("f=%f\n",f);
printf("g=%f\n",g);
printf("\n");
}
Execute program, output as:
RUN¿
a=1023
a=1777
a=3ff
b=2222
c=123
d=1234
e=x
f=3.141593
g=3.141593