gpt4 book ai didi

c - C中的宽度格式化程序

转载 作者:太空宇宙 更新时间:2023-11-04 00:58:53 25 4
gpt4 key购买 nike

我遇到了一个奇怪的问题。

给出这个程序:

#include <stdio.h>

int main()
{
printf("%04d",100);
return 0;
}

输出是0100,我能理解为什么。如果我把它改成

printf("%04.1d",100);

我得到的输出是 100,1 前面有一个空格。0 被忽略。我的问题是宽度格式化程序在这些情况下如何工作?

最佳答案

对于 %d,如果指定了精度(指定最小字符数),则忽略 0 标志,因为它执行类似的功能。

手册页关于 0 标志的说明如下:

The value should be zero padded. For d, i, o, u, x, X, a, A, e, E, f, F, g, and G conversions, the converted value is padded on the left with zeros rather than blanks. If the 0 and - flags both appear, the 0 flag is ignored. If a precision is given with a numeric conversion (d, i, o, u, x, and X), the 0 flag is ignored. For other conversions, the behavior is undefined.

以及以下关于精度的内容:

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 '.', the precision is taken to be zero. A negative precision is taken as if the precision were omitted. 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.

在您的情况下,由于您将精度指定为 1,因此至少需要打印 1 个字符。如果您使用 4 作为精度,您将得到一个前导零。

关于c - C中的宽度格式化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48629089/

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