Functions แบ่ง 2 ประเภท: Predefined (Library) และ User-defined
Predefined Functions
- อยู่ใน system libraries (header files)
- นำมาใช้ได้เลย ต้องรู้ syntax และ include header ที่ถูกต้อง
ตัวอย่างฟังก์ชันยอดนิยม
| Function | Header | คำอธิบาย |
|---|---|---|
| sqrt(x) | math.h | รากที่สอง (x ≥ 0) |
| cbrt(x) | math.h | รากที่สาม |
| pow(x,y) | math.h | x ยกกำลัง y |
| log(x) | math.h | ลอการิทึมฐาน e |
| ceil(x) | math.h | ปัดขึ้นจำนวนเต็ม |
| printf/scanf | stdio.h | I/O |
| clrscr/getch | conio.h | Console I/O (Turbo C) |
โปรแกรมที่ 1: ใช้ sqrt()
#include <stdio.h>
#include <conio.h>
#include <math.h>
main() {
int x, y;
clrscr();
printf("Enter a positive number: ");
scanf("%d", &x);
y = sqrt(x);
printf("Square root = %d", y);
getch();
}
ผลลัพธ์
Enter a positive number: 25
Square root = 5
โปรแกรมที่ 2: ใช้หลายฟังก์ชัน math.h
#include <stdio.h>
#include <math.h>
main() {
int x, y, z, n, k, p, r, q;
printf("Enter x and n values: ");
scanf("%d %d", &x, &y);
y = cbrt(x);
z = exp(x);
k = log(x);
p = ceil(x);
q = pow(x, r); // r ต้องกำหนดค่าก่อน
printf("cuberoot = %d\n", y);
printf("exponent = %d\n", z);
printf("log = %d\n", k);
printf("ceil = %d\n", p);
printf("power = %d\n", q);
}
ผลลัพธ์ (x=9, n=2)
cuberoot = 2
exponent = 8103
log = 2
ceil = 9
power = 81