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

标签 c

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

给出这个程序:

#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/

相关文章:

c - 如何在 VS 2022 中正确安装附加 C 头文件

java - 为什么Java程序的执行时间比C语言中的相同程序要长?

c - 如何在c中输入两个空格分隔的单词有时可以省略一个单词

c - 如何在巨型循环中使用 GDB

c - 如何使用 C 在 MPI 中发送(MPI_Send)具有指针字段的嵌套结构

有人可以解释这个 OpenCL 程序有什么问题吗?

C 窗口 : generate a child process in order to stop and restart (after timeout) the parent process

java - 如何通过C函数调用方便OCamljava编译ocaml库?

c - 如何查看数字 x 的二进制补码是否可以用 n 位表示

c - For 循环未被执行 C