อะไรคือความแตกต่างระหว่าง%dและ%iเมื่อใช้เป็นตัวระบุรูปแบบในprintf?
อะไรคือความแตกต่างระหว่าง%dและ%iเมื่อใช้เป็นตัวระบุรูปแบบในprintf?
คำตอบ:
printfพวกเขาเป็นคนเดียวกันเมื่อนำมาใช้สำหรับการส่งออกเช่นกับ
อย่างไรก็ตามสิ่งเหล่านี้จะแตกต่างกันเมื่อใช้เป็นตัวระบุอินพุตเช่นด้วยscanfโดยที่%dสแกนเลขจำนวนเต็มเป็น%iเลขฐานสิบที่ลงนามแล้ว แต่ค่าเริ่มต้นเป็นทศนิยม แต่ยังอนุญาตเลขฐานสิบหก (หากนำหน้าด้วย0x) และฐานแปด (หากนำหน้าด้วย0)
ดังนั้น033จะเป็น 27 %iแต่ 33 %dพร้อมด้วย
printf scanf
เหล่านี้เป็นเหมือนแต่แตกต่างกันสำหรับprintf scanfสำหรับprintfทั้ง%dและ%iกำหนดจำนวนเต็มทศนิยมที่ลงนาม สำหรับscanf, %dและ%iยังหมายถึงการลงนามจำนวนเต็ม แต่%iinteprets การป้อนข้อมูลที่เป็นเลขฐานสิบหกถ้านำหน้าด้วย0xและฐานแปดถ้านำหน้าด้วย0และอื่น ๆ ตีความการป้อนข้อมูลที่เป็นทศนิยม
มีความแตกต่างระหว่างไม่เป็น%iและ%dspecifiers printfรูปแบบ เราสามารถเห็นสิ่งนี้ได้โดยไปที่ร่างมาตรามาตรฐาน C99 7.19.6.1 ฟังก์ชั่น fprintfซึ่งครอบคลุม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ถือว่าฐาน 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.
ไม่มีในprintf- ทั้งสองมีความหมายเหมือนกัน
scanf()สตริงรูปแบบตามที่คำตอบที่ยอมรับบอกว่า