Skip to content

C-1.2 printf Formats

ข้อมูลเดียวกันแต่แสดงต่างกันได้ — นี่คือแนวคิดพื้นฐานที่สุดของ “stored vs displayed” และ C คือที่ที่มันเกิดขึ้นครั้งแรก

ใน C, printf() ไม่ได้รู้อัตโนมัติว่าคุณอยากแสดงข้อมูลแบบไหน คุณต้อง บอกมัน ด้วย format specifier:

Specifierใช้กับแสดงผลเป็น
%dintตัวเลขจำนวนเต็ม (decimal)
%ffloat, doubleทศนิยม
%ccharตัวอักษร 1 ตัว
%schar[] / char*ข้อความ (string)
%zusize_tขนาด (จาก sizeof)
%xintเลขฐาน 16 (hexadecimal)
%ointเลขฐาน 8 (octal)

ข้อมูลเดียวกัน — 4 หน้าตา

Section titled “ข้อมูลเดียวกัน — 4 หน้าตา”

นี่คือ insight ที่สำคัญที่สุดของบทเรียนนี้:

#include <stdio.h>
int main() {
char ch = 65; // เก็บเลข 65 ลงใน char
printf("As integer (%%d): %d\n", ch); // 65
printf("As character (%%c): %c\n", ch); // A
printf("As hex (%%x): %x\n", ch); // 41
printf("As octal (%%o): %o\n", ch); // 101
printf("\n--- ข้อมูลเดียวกัน 4 แบบ ---\n");
printf("Memory: เก็บ bits เดียวกันทุกบรรทัด\n");
printf("ต่างกันแค่: วิธีที่เรา *อ่าน* มัน\n");
return 0;
}

ผลลัพธ์:

As integer (%d): 65
As character (%c): A
As hex (%x): 41
As octal (%o): 101

สิ่งสำคัญ: ตัวแปร ch เก็บ bits เดียวกันทุกกรณี — 01000001 — ต่างกันแค่วิธีที่ printf แสดงผล มัน

นี่คือแนวคิด stored vs displayed ที่ทุกเครื่องมืออื่นสืบทอดมา

#include <stdio.h>
int main() {
double price = 1234.5;
printf("Default: %f\n", price); // 1234.500000
printf("2 decimals: %.2f\n", price); // 1234.50
printf("No decimals: %.0f\n", price); // 1235 (rounded!)
printf("Width 10: %10.2f\n", price); // ' 1234.50'
printf("Left align: %-10.2f|\n", price); // '1234.50 |'
// Scientific notation
printf("Scientific: %e\n", price); // 1.234500e+03
return 0;
}

ผลลัพธ์:

Default: 1234.500000
2 decimals: 1234.50
No decimals: 1235
Width 10: 1234.50
Left align: 1234.50 |
Scientific: 1.234500e+03

สังเกต: %.0f ได้ 1235 ไม่ใช่ 1234 — printf ปัดเศษ ให้อัตโนมัติ

นี่คือต้นกำเนิดของ:

  • Sheets: Format > Number > ทศนิยม 2 ตำแหน่ง
  • Python: f"{price:.2f}"
  • SQL: ROUND(price, 2)

ทุกเครื่องมือสืบทอดแนวคิดนี้มาจาก printf

ระวัง: Wrong Format = Wrong Output

Section titled “ระวัง: Wrong Format = Wrong Output”
#include <stdio.h>
int main() {
int num = 42;
float pi = 3.14f;
// ถูก
printf("int with %%d: %d\n", num); // 42
printf("float with %%f: %f\n", pi); // 3.140000
// ผิด! — ใช้ format ไม่ตรงกับ type
printf("int with %%f: %f\n", num); // ขยะ! (undefined behavior)
printf("float with %%d: %d\n", pi); // ขยะ!
return 0;
}

C ไม่ตรวจให้คุณ — คุณต้องจับคู่ format กับ type เอง ภาษาอื่นๆ เรียนรู้จากจุดอ่อนนี้ แล้วทำให้ type checking เป็นอัตโนมัติ