在printf和scanf中使用%d和%i作为格式说明符时,它们之间有什么区别?


printf中没有-这两个是同义词。


这些对printf是相同的,但对scanf是不同的。对于printf, %d和%i都指定有符号十进制整数。对于scanf, %d和%i也表示有符号整数,但%i如果前面有0x则将输入解释为十六进制数,如果前面有0则将输入解释为八进制,否则将输入解释为十进制。


它们用于输出时是相同的,例如printf。

然而,当用作输入说明符时,这些是不同的,例如使用scanf,其中%d将整数扫描为带符号的十进制数,但%i默认为十进制,但也允许十六进制(如果前面有0x)和八进制(如果前面有0)。

所以033是27和%i,但是33和%d。


printf的%i和%d格式说明符之间没有区别。我们可以在C99标准草案第7.19.6.1节中看到fprintf函数,该函数也涵盖了关于格式说明符的printf,它在第8段中说:

转换说明符及其含义如下:

并包括以下项目:

d,i int参数在样式中转换为带符号的十进制 −dddd。精度指定最小位数 出现;如果转换的值可以用更少的单位表示 数字,用前导零展开。默认精度为 1. 将零值转换为精度为零的结果是 没有字符。

另一方面,对于scanf有一个区别,%d假设底数为10,而%i自动检测底数。我们可以通过第7.19.6.2节看到这一点,fscanf函数涵盖了关于格式说明符的scanf,在第12段中它说:

转换说明符及其含义如下:

并包括以下内容:

d Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of the strtol function with the value 10 for the base argument. The corresponding argument shall be a pointer to signed integer. i Matches an optionally signed integer, whose format is the same as expected for the subject sequence of the strtol function with the value 0 for the base argument. The corresponding argument shall be a pointer to signed integer.