[c语言] printf格式化输出

函数原型

int printf(const char *format, [argument]);

argument 说明

%[flags] [width] [.precision] [modifier] type

  • [flags] control convertion (optional)
  • [width] number of characters to output (optional)
  • [.precision] precision of number (optional)
  • [modifier] overrides size (type) of argument (optional)
  • type type of conversion (required)

flags 转换控制

  • none, 右对齐,左边填充0space
  • -, 左对齐(默认右对齐),右边填充space
  • +, 在数字前显示+-符号,默认只有负数时显示符号
  • space, 只对负数显示符号
  • # convert to alternative form:

csdu类无影响;
o类,在输出时加前缀o
x类,在输出时加前缀0x
egf类当结果有小数时才给出小数点

  • 0, 转换使用前导0来填充字符宽度,而不是space

width 字符输出宽度

.precision 数字输出精度 可选

精度格式符以.开头,后跟十进制整数。

本项的意义是:

如果输出数字,则表示小数的位数
如果输出的是字符,则表示输出字符的个数
若实际位数大于所定义的精度数,则截去超过的部分。

  • none
  • .0
  • .N

modifier 修饰符

  • hh
  • h
  • l
  • ll
  • L
  • j
  • t
  • z

type 转换类型

  • d/i 有符号10进制整数
  • o 有符号8进制整数
  • u 无符号10进制整数
  • x 无符号的16进制数字,并以小写abcdef表示
  • X 无符号的16进制数字,并以大写ABCDEF表示
  • F/f 浮点数
  • E/e 用科学表示格式的浮点数
  • g 使用%f和%e表示中的总的位数表示最短的来表示浮点数 G 同g格式,但表示为指数
  • c 单个字符
  • s 字符串
  • % 显示百分号本身
  • p 显示一个指针,near指针表示为:XXXX
  • n 相连参量应是一个指针,其中存放已写字符的个数

实例

Example

    printf("%04d
", -3);

说明:0, flag; 4, width; d, type

输出: -003

Example

    printf("%#5x
", 13);

说明:#, flag; 5, width; x, type

输出: 0xd

Example

    printf("%.3f
", 1.312321);
    printf("%.3s
", "hello, world");

说明:.3, precision; f/s, type
输出: 1.312hel

Good Good Study! Day Day Up!

原文地址:https://www.cnblogs.com/kdurant/p/4150589.html