在printf和scanf中,%d和%i作为格式说明符时有什么区别?
在输出时,例如使用printf
,它们是相同的。
然而,在作为输入指示符时,例如使用scanf
,它们是不同的。其中,%d
将带符号的十进制数作为整数进行扫描,但%i
默认为十进制,同时允许以十六进制(如果前缀为0x
)和八进制(如果前缀为0
)表示。
因此,对于033
,使用%i
将得到27,但使用%d
将得到33。
对于printf
,%d
和%i
都表示有符号十进制整数。但是对于scanf
,%d
和%i
同样表示有符号整数,但是如果%i
前面有0x
,则将其解释为十六进制数;如果前面有0
,则将其解释为八进制数;如果没有前缀,则将其解释为十进制数。
%i
和%d
对于printf
格式说明符来说没有区别。我们可以通过查看C99标准草案第7.19.6.1
节The fprintf function来了解这一点,该节还涵盖了有关格式说明符的printf
,其中第8段落写道:
转换说明符及其含义如下:
并包括以下内容:
另一方面,对于d,i The int argument is converted to signed decimal in the style [−]dddd. The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it is expanded with leading zeros. The default precision is 1. The result of converting a zero value with a precision of zero is no characters.
scanf
而言,有所不同,%d
会假设为十进制,而%i
则会自动检测进制。我们可以在第7.19.6.2
节中查看相关内容,该部分包含了关于格式说明符的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.
printf
中没有任何区别,这两个词是同义词。
scanf()
格式字符串中使用时会有所不同。 - J...S
printf
和scanf
的文档中看到。 - Gabriel Staples