Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

การตรวจสอบว่า double (หรือ float) เป็น NaN ใน C++

บทนำ

เพื่อตรวจสอบว่าตัวเลขจุดลอยตัวหรือ double เป็น NaN (Not a Number) ใน C++ เราสามารถใช้ฟังก์ชัน isnan() ได้ ฟังก์ชัน isnan() อยู่ในไลบรารี cmath ฟังก์ชันนี้เพิ่มเข้ามาตั้งแต่ C++11 ดังนั้นจาก C++11 เป็นต้นไปสามารถใช้ได้

ตัวอย่างโค้ด

#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;
}

ผลลัพธ์

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