C语言中%d和%.d的区别

Difference between %d and %.d in C language

我写了下面的代码并收到了一个空白输出:

int main(){

    int y=0;

    printf("%.d", y);

    return 0;
}

相反,如果我只使用 %d,我会得到 0 作为输出。

%d%.d有什么区别。

非常感谢您的建议!

一个.之前的转换说明符叫做"precision"。来自 printf man page(强调我的):

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,

d, i

The int argument is converted to signed decimal notation. The precision, if any, gives the minimum number of digits that must appear; if the converted value requires fewer digits, it is padded on the left with zeros. The default precision is 1. When 0 is printed with an explicit precision 0, the output is empty

因此对于示例代码,%.d 表示精度为零的整数转换。零精度意味着最少的零位。由于要转换的值为 0,因此由于精度为零,因此根本不会显示。相反,%d 没有明确的精度,因此默认精度为 1,导致打印 0.