gpt4 book ai didi

c++ - printf 的整数参数的零填充宽度和精度是否相同?

转载 作者:太空狗 更新时间:2023-10-29 21:24:44 25 4
gpt4 key购买 nike

我最近偶然发现了这样的代码:

uint32_t val;
...
printf("%.08X", val);

这让我很困惑。我的意思是,要么指定 0+width 要么指定精度,两者的意义何在?

Width :

The width argument ... controls the minimum number of characters that are output. If the number of characters in the output value is less than the specified width, blanks are added ... . If width is prefixed by 0, leading zeros are added ... .

The width specification never causes a value to be truncated. ...

Precision :

... It consists of a period (.) followed by a non-negative decimal integer that, depending on the conversion type, specifies ... the number of significant digits to be output.

The type determines either the interpretation of precision or the default precision when precision is omitted ...

d, i, u, o, x, X - The precision specifies the minimum number of digits to be printed. If the number of digits in the argument is less than precision, the output value is padded on the left with zeros. The value is not truncated when the number of digits exceeds precision.

所以我要么使用 "%08X" 要么 "%.8X""%08X" 对我来说没有任何意义。

然而,它似乎没有任何区别,也就是说,所有三个变体似乎都产生相同的输出。

最佳答案

你是对的:

“%08X”“%.8X”“%.08X”

是等价的。

至于为什么 - 引用这个:

http://www.cplusplus.com/reference/cstdio/printf/

因此:

在情况 1 中,这个使用指定宽度:

Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.

因此:

%08X 将打印最少 8 个字符

来自这个引用:

For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0. For a, A, e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6). For g and G specifiers: This is the maximum number of significant digits to be printed. For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered. If the period is specified without an explicit value for precision, 0 is assumed.

%.8X 使用精度说明符。因此,它也将打印至少 8 个字符。

最后:

%.08X 还将打印至少 8 个字符(同样,由于精度说明符)。为什么?因为 08 被解释为 8 - 导致与之前相同的输出。这对于个位数精度规范输出似乎没有意义,但在这样的情况下:

%0.15X

可以很重要。

存在这些不同的格式以允许更好地控制输出(在我看来 - 这是一种非常类似于 Fortran 的继承)。

但是,正如您所发现的,这种为更好地控制精度而进行的过度补偿允许您获得相同的输出 - 但具有不同的标志。

更新:

正如 hvd 所指出的,我忘了提及:X 说明符需要一个无符号值,因此在这种情况下,您的输出与 %08X%.8X(因为没有符号)。但是,对于类似的内容:%08d%.8d - 它不是:一个填充到 8 位数字,另一个填充到 8 个字符,所以它们对于负值表现不同。

关于c++ - printf 的整数参数的零填充宽度和精度是否相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15333023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com