函数原型
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, 右对齐,左边填充0和space-, 左对齐(默认右对齐),右边填充space+, 在数字前显示+和-符号,默认只有负数时显示符号space, 只对负数显示符号#convert to alternative form:
对
c、s、d、u类无影响;
对o类,在输出时加前缀o;
对x类,在输出时加前缀0x;
对e、g、f类当结果有小数时才给出小数点
0, 转换使用前导0来填充字符宽度,而不是space
width 字符输出宽度
.precision 数字输出精度 可选
精度格式符以.开头,后跟十进制整数。
本项的意义是:
如果输出数字,则表示小数的位数
如果输出的是字符,则表示输出字符的个数
若实际位数大于所定义的精度数,则截去超过的部分。
none.0.N
modifier 修饰符
hhhlllLjtz
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指针表示为:XXXXn相连参量应是一个指针,其中存放已写字符的个数
实例
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.312 和 hel