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
| Biểu thức | Kết quả | Floating-point exception |
islessgreater(NaN, y) | false | Không (quiet) |
islessgreater(x, NaN) | false | Không (quiet) |
x != y (với NaN) | true | Có thể raise FE_INVALID |
x < y || x > y | true (với NaN) | Raise FE_INVALID |
Các hàm so sánh quiet khác (C99/C++11)
| Hàm | Kiểm tra | NaN behavior |
isless(x, y) | x < y | false, quiet |
isgreater(x, y) | x > y | false, quiet |
islessequal(x, y) | x ≤ y | false, quiet |
isgreaterequal(x, y) | x ≥ y | false, quiet |
islessgreater(x, y) | x < y ∨ x > y | false, quiet |
isunordered(x, y) | x hoặc y là NaN | true nếu NaN, quiet |
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);
}