6. printf (เป็นฟังก์ชันมาตรฐานของ C ใน stdio)
◦ประกาศ stdio ในส่วน Preprocessor Directive
◦ก่อนเรียกใช้ฟังก์ชัน printf ใน main
รูปแบบ printf(“control string”, variable,…);
◦variable เป็นตัวแปรใช้เก็บค่า (ที่เปลี่ยนแปลงได้) ใน
Memory ในขณะประมวลผล
6
control string ประกอบด้วย
ข้อความอธิบาย เช่น printf(“C Programming”);
%format เช่น %d, %f, %c, %s
อักษรควบคุม เช่น n (new line), …
%d สาหรับ integer หรือ decimal
%f สาหรับ real หรือ floating point
…
Memor
y
variable
7.
8. ในส่วนรูปแบบข้อความอธิบายนั้น อาจจะเป็นตัวอักษร ข้อความ ตัวเลข หรือ
เป็นตัวกาหนดชนิดของข้อมูล ซึ่งใช้กาหนดชนิดข้อมูลที่จะพิมพ์ ซึ่งจะต้องอยู่
หลังครื่องหมาย % เสมอและสามารถใช้ได้ทั้ง การรับและแสดงผลข้อมูล ดัง
แสดงในตาราง
ชนิดข้อมูล ขนาด รหัส ตัวอย่าง
char - c %c
short int
int
long int
h
-
i or l
d
d
d
%hd
%d
%ld
float
double
long double
-
-
l
f
f
f
%f
%f
%lf
9. d /* int, signed base 10 */
i /* int, signed base 10 */
o /* int, unsigned base 8, no leading 0 */
x /* int, unsigned base 16, abcdef with no leading 0x */
X /* int, unsigned base 16, ABCDEF with no leading 0X */
u /* int, unsigned base 10 */
s /* char *, nul terminated sequence of characters */
c /* int, single character */
f /* double, notation [-]mm.dd */
e /* double, notation [-]m.dde[+/-]xx */
E /* double, notation [-]m.ddE[+/-]xx */
g /* double, %e if exponent is less than -4 or >= the precision, %f otherwise */
G /* double, %E if exponent is less than -4 or >= the precision, %f otherwise */
p /* void *, implementation dependent representation */
n /* int *, the number of characters written so far. Assigned to the argument */
% /* print a % character */