3 回答

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超4個(gè)贊
當(dāng)用于輸出時(shí)它們是相同的,例如printf
。
但是,當(dāng)用作輸入說明符時(shí),這些是不同的,例如scanf
,其中,%d
將整數(shù)掃描為帶符號(hào)的十進(jìn)制數(shù),但%i
默認(rèn)為十進(jìn)制,但也允許十六進(jìn)制(如果前面帶有0x
)和八進(jìn)制(如果前面帶有0
)。
所以033
27 %i
歲,但33歲%d
。

TA貢獻(xiàn)2051條經(jīng)驗(yàn) 獲得超10個(gè)贊
%i
和%d
格式說明符之間沒有區(qū)別printf
。我們可以通過參考草案C99標(biāo)準(zhǔn)部分來看到這一點(diǎn)7.19.6.1
.fprintf函數(shù)也涉及printf
格式說明符,它在第8段中說:
轉(zhuǎn)換說明符及其含義是:
并包括以下項(xiàng)目:
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
假設(shè)基數(shù)為10而%i
自動(dòng)檢測(cè)基數(shù)。我們可以通過將部分看到這個(gè)7.19.6.2
fscanf函數(shù)覆蓋scanf
相對(duì)于格式說明,在第12這樣說的:
轉(zhuǎn)換說明符及其含義是:
并包括以下內(nèi)容:
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.

TA貢獻(xiàn)1806條經(jīng)驗(yàn) 獲得超5個(gè)贊
在我看來,在sscanf中可能出現(xiàn)零填充的int似乎是最合理的默認(rèn)行為。如果你不期待Octal,那可能會(huì)導(dǎo)致微妙的錯(cuò)誤。所以這表明%d是一個(gè)很好的說明符,當(dāng)你必須任意選擇一個(gè)時(shí),除非你明確想要讀取八進(jìn)制和/或十六進(jìn)制。
- 3 回答
- 0 關(guān)注
- 1127 瀏覽
添加回答
舉報(bào)