C language printf() function output result format detailed explanation

First summarize the various format control characters

%d : Output according to the actual length of the integer data.
%ld : Output long integer data.
%f : used to output real numbers, including single precision and double precision, output in decimal form. The system defaults to output all the integer part, and the decimal part to 6 digits, rounding over 6 digits.
(Here is an off topic, remember to use %lf for double type data input and %f for output, and %f for float type input and output. )
%O : output as an octal integer.
%s : used to output character strings.
%x (or %X or %#x or %#X) : Output integers in hexadecimal form. For specific differences, please see the supplement at the end of the article↓

①How to make the output data right-aligned?

%md : Only need to add a number m between the format control characters to specify the width of the output field.

#include <stdio.h>
int main(void)
{
    
    
    int n1 = 7;
    int n2 = 777;
    int n3 = 7777777;
    printf("%8d\n", n1);
    printf("%8d\n", n2);
    printf("%8d\n", n3);
    return 0;
}

运行结果为:
       7
     777
 7777777

②How to make the output data right-aligned, and fill the empty bits with 0?

%0md : Specify the width of the output field plus a 0 before the number m.

#include <stdio.h>
int main(void)
{
    
    
    int n1 = 7;
    int n2 = 777;
    int n3 = 7777777;
    printf("%8d\n", n1);
    printf("%8d\n", n2);
    printf("%8d\n", n3);
    return 0;
}

运行结果为:
00000007
00000777
07777777

③How to control the number of decimal places of floating point numbers?

%.nf : Specify the number of decimal places to output as n, and the last digit is rounded.

#include <stdio.h>
int main(void)
{
    
    
    float n1 = 7;
    float n2 = 7.7777;
    float n3 = 77.77777;
    printf("%8f\n", n1);            //小数点占一位,小数部分也占位
    printf("%.3f\n", n2);
    printf("%08.3f\n", n3);           
    return 0;
}

运行结果为:
7.000000
7.778
0077.778

↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
↓↓↓↓↓↓↓↓↓↓↓↓↓↓ ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
Supplementary knowledge of output hexadecimal output control symbol:

#include <stdio.h>
int main(void)
{
    
    
    int i = 77;
    printf("%x\n", i);    //%小写的x
    printf("%X\n", i);    //%大写的X
    printf("%#x\n", i);   //#小写的x
    printf("%#X\n", i);   //#大写的X
    return 0;
}

运行结果为:
2f
2F
0x2f
0X2F

It can be seen from the output result:
if it is a lowercase x, the output letter is lowercase; if it is an uppercase X, the output letter is uppercase; if you add a #, it will be output in standard hexadecimal format.

Guess you like

Origin blog.csdn.net/kyc592/article/details/111536596
Recommended