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

nextafter() và nexttoward() trong C/C++

Hai hàm trong <math.h>/<cmath> tìm số biểu diễn được tiếp theo sau a theo hướng b. nexttoward() chính xác hơn cho tham số 2.

Ví dụ

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

int main() {
    printf("nextafter(0, 1)   = %e\n", nextafter(0.0, 1.0));    // 4.94e-324
    printf("nextafter(0, -1)  = %e\n", nextafter(0.0, -1.0));   // -4.94e-324
    printf("nextafter(0.8, 0) = %e\n", nextafter(0.8, 0.0));    // 0.8 (prev)

    printf("nexttoward(0, 1)  = %e\n", nexttoward(0.0, 1.0));
    printf("nexttoward(0, -1) = %e\n", nexttoward(0.0, -1.0));
    printf("nexttoward(0.8,0) = %e\n", nexttoward(0.8, 0.0));
    return 0;
}

Kết quả

nextafter(0, 1)   = 4.940656e-324
nextafter(0, -1)  = -4.940656e-324
nextafter(0.8, 0) = 8.000000e-001
nexttoward(0, 1)  = 4.940656e-324
nexttoward(0, -1) = -4.940656e-324
nexttoward(0.8,0) = 8.000000e-001