格式化整数时printf中的精度字段 [英] Precision field in printf when formatting integer

查看:62
本文介绍了格式化整数时printf中的精度字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我执行这两行时:

printf("%.5d\n", 3);  // use of precision filed
printf("%05d\n", 3);  // use of 0 flag to prepend with 0

我得到以下输出:

00003
00003

同样的结果

所以我想知道整数类型的精度字段是什么意思

So I wonder what is the meaning of the precision field for integer types

推荐答案

对于 %d,精度是要打印的最小位数.

For %d, the precision is the minimum number of digits to print.

来自手册页:

精度

一个可选的精度,形式为句点 ('.') 后跟一个可选的十进制数字字符串.代替十进制数字字符串可以写*"或*m$"(对于一些十进制整数m)到指定精度在下一个参数中给出,或在分别为第 m 个参数,必须是 int 类型.如果精度仅作为."给出,或者精度为负,则精度为零.这给出了最小数量为 d、i、o、u、x 和 X 转换出现的数字,出现在 a、A、e、E、f 和 F 的基数字符之后的数字转换,g 和 G 的最大有效位数转换,或要打印的最大字符数用于 s 和 S 转换的字符串.

An optional precision, in the form of a period ('.') followed by an optional decimal digit string. Instead of a decimal digit string one may write "*" or "*m$" (for some decimal integer m) to specify that the precision is given in the next argument, or in the m-th argument, respectively, which must be of type int. If the precision is given as just '.', or the precision is negative, the precision is taken to be zero. This gives the minimum number of digits to appear for d, i, o, u, x, and X conversions, the number of digits to appear after the radix character for a, A, e, E, f, and F conversions, the maximum number of significant digits for g and G conversions, or the maximum number of characters to be printed from a string for s and S conversions.

对于正值,这与为字段宽度和 0 标志提供相同的值相同.如果值为负,负号将占%05d宽度的一个字符.

For positive values, this works out to be the same as giving the same value for the field width and a 0 flag. If the value is negative, the negative sign will take up one character in the width of %05d.

printf("%.5d\n", -3);  // use of precision filed
printf("%05d\n", -3);  // use of 0 flag to prepend with 0

输出:

-00003
-0003

这篇关于格式化整数时printf中的精度字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆