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

Kiểm tra double/float có phải NaN trong C++


Để kiểm tra số thực float/double có phải NaN (Not a Number) trong C++, dùng hàm isnan() từ thư viện cmath (từ C++11).

Ví dụ

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

int main() {
    if (isnan(sqrt(30))) {
        cout << "Square root of 30 is not a number" << endl;
    } else {
        cout << "Square root of 30 is a number" << endl;
    }
    if (isnan(sqrt(-30))) {
        cout << "Square root of -30 is not a number" << endl;
    } else {
        cout << "Square root of -30 is a number" << endl;
    }
    return 0;
}

Kết quả

Square root of 30 is a number
Square root of -30 is not a number