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

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


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

ตัวอย่าง

#include <cmath>
#include <iostream>
using namespace std;
main() {
   if(isnan(sqrt(30))) { //square root of 30 is a floating point number
      cout << "Square root of 30 is not a number" <<endl;
   } else {
      cout << "Square root of 30 is a number" <<endl;
   }
   if(isnan(sqrt(-30))) { //square root of -30 is an imaginary number
      cout << "Square root of -30 is not a number" <<endl;
   } else {
      cout << "Square root of -30 is a number" <<endl;
   }
}

ผลลัพธ์

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