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

Hàm islessgreater() trong C/C++

islessgreater(x, y) kiểm tra x < y HOẶC x > y (tức là x ≠ y), không ném ngoại lệ floating-point (quiet comparison). Header: <math.h> (C) / <cmath> (C++).

Cú pháp

// C (macro/function-like)
int islessgreater(real-floating x, real-floating y);

// C++ (overload cho float, double, long double)
bool islessgreater(float x, float y);
bool islessgreater(double x, double y);
bool islessgreater(long double x, long double y);

Ví dụ

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    int val1 = 28, val2 = 8;
    bool result = islessgreater(val1, val2);
    cout << "28 != 8 ? " << result << endl; // 1 (true)
    
    val1 = 8; val2 = 8;
    result = islessgreater(val1, val2);
    cout << "8 != 8 ? " << result << endl; // 0 (false)
    
    // Với NaN
    double nan = std::nan("");
    cout << "NaN != 5 ? " << islessgreater(nan, 5.0) << endl; // 0 (false, không raise FE_INVALID)
    cout << "5 != NaN ? " << islessgreater(5.0, nan) << endl; // 0 (false)
    
    // So sánh với !=
    cout << "NaN != 5 (operator): " << (nan != 5.0) << endl; // 1 (true!) - khác behavior
    
    return 0;
}

Kết quả

28 != 8 ? 1
8 != 8 ? 0
NaN != 5 ? 0
5 != NaN ? 0
NaN != 5 (operator): 1

Điểm khác biệt quan trọng: NaN handling

Các hàm so sánh quiet khác (C99/C++11)

Biểu thứcKết quảFloating-point exception
islessgreater(NaN, y)falseKhông (quiet)
islessgreater(x, NaN)falseKhông (quiet)
x != y (với NaN)trueCó thể raise FE_INVALID
x < y || x > ytrue (với NaN)Raise FE_INVALID

Khi nào dùng?

  • So sánh floating-point nơi NaN có thể xuất hiện (khoa học, graphics)
  • Tránh branch misprediction từ exception handling
  • Viết code numeric robust
  • Kết hợp với isunordered để kiểm tra NaN trước

Ví dụ ứng dụng: Sort an toàn NaN

bool nanSafeLess(double a, double b) {
    if (isunordered(a, b)) return false; // NaN coi như "lớn nhất" hoặc "nhỏ nhất"
    return isless(a, b);
}
HàmKiểm traNaN behavior
isless(x, y)x < yfalse, quiet
isgreater(x, y)x > yfalse, quiet
islessequal(x, y)x ≤ yfalse, quiet
isgreaterequal(x, y)x ≥ yfalse, quiet
islessgreater(x, y)x < y ∨ x > yfalse, quiet
isunordered(x, y)x hoặc y là NaNtrue nếu NaN, quiet