Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Các hàm trunc(), truncf(), truncl() trong C

Ở đây ta sẽ xem 3 hàm: trunc(), truncf() và truncl(). Chúng dùng để chuyển giá trị dấu ch động sang dạng cắt bỏ phần thập phân (truncated).

Hàm trunc()

Dùng cho kiểu double. Trả về phần nguyên. Cú pháp:

double trunc(double argument)

Ví dụ

#include <stdio.h>
#include <math.h>

int main() {
    double a, b, x = 53.26, y = 75.86;
    a = trunc(x);
    b = trunc(y);
    printf("The value of a: %lf\n", a);
    printf("The value of b: %lf\n", b);
    return 0;
}

Kết quả

The value of a: 53.000000
The value of b: 75.000000

Hàm truncf()

Dùng cho kiểu float. Cú pháp:

float truncf(float argument)

Ví dụ

#include <stdio.h>
#include <math.h>

int main() {
    float a, b, x = 53.26f, y = 75.86f;
    a = truncf(x);
    b = truncf(y);
    printf("The value of a: %f\n", a);
    printf("The value of b: %f\n", b);
    return 0;
}

Kết quả

The value of a: 53.000000
The value of b: 75.000000

Hàm truncl()

Dùng cho kiểu long double. Cú pháp:

long double truncl(long double argument)

Ví dụ

#include <stdio.h>
#include <math.h>

int main() {
    long double a, b, x = 53547.55555555555L, y = 78547.55555555523L;
    a = truncl(x);
    b = truncl(y);
    printf("The value of a: %Lf\n", a);
    printf("The value of b: %Lf\n", b);
    return 0;
}

Kết quả

The value of a: 53547.000000
The value of b: 78547.000000