Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

Predefined Functions (Library Functions) ในภาษา C

Functions แบ่ง 2 ประเภท: Predefined (Library) และ User-defined

Predefined Functions

  • อยู่ใน system libraries (header files)
  • นำมาใช้ได้เลย ต้องรู้ syntax และ include header ที่ถูกต้อง

ตัวอย่างฟังก์ชันยอดนิยม

FunctionHeaderคำอธิบาย
sqrt(x)math.hรากที่สอง (x ≥ 0)
cbrt(x)math.hรากที่สาม
pow(x,y)math.hx ยกกำลัง y
log(x)math.hลอการิทึมฐาน e
ceil(x)math.hปัดขึ้นจำนวนเต็ม
printf/scanfstdio.hI/O
clrscr/getchconio.hConsole 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