isfinite() คืออะไร?
isfinite() เป็นฟังก์ชันในตัวใน C++ ซึ่งอยู่ในไฟล์หัวข้อ <cmath> ฟังก์ชันนี้ใช้ตรวจสอบและส่งคืนว่า ตัวเลขที่กำหนดเป็นจำกัด (finite) หรือไม่ ตัวเลขจำกัด (finite number) คือ ตัวเลขจุดลอยตัวที่ ไม่ใช่ infinity และไม่ใช่ NaN (Not a Number)
ไวยากรณ์ (Syntax)
bool isfinite(float x); bool isfinite(double x); bool isfinite(long double x);
ฟังก์ชันนี้รับพารามิเตอร์เพียงหนึ่งตัว x ซึ่งเป็นค่าที่ต้องการตรวจสอบว่าเป็นจำกัดหรือไม่
ค่าที่ส่งคืน (Return Value)
ฟังก์ชันส่งคืนค่าบูลีน: 0 (false) หากตัวเลขไม่ใช่จำกัด (คือเป็น infinity หรือ NaN) และ 1 (true) หากตัวเลขเป็นจำกัด
ตัวอย่างที่ 1: ตรวจสอบการหารปกติ vs หารด้วยศูนย์
#include <cmath>
#include <iostream>
using namespace std;
int main() {
float a = 10.0f, b = 0.1f, c = 0.0f;
isfinite(a / b) ? cout << "\nผลลัพธ์ a/b เป็นจำกัด" : cout << "\nผลลัพธ์ a/b ไม่ใช่จำกัด";
isfinite(a / c) ? cout << "\nผลลัพธ์ a/c เป็นจำกัด" : cout << "\nผลลัพธ์ a/c ไม่ใช่จำกัด";
return 0;
}
ผลลัพธ์ (Output)
ผลลัพธ์ a/b เป็นจำกัด ผลลัพธ์ a/c ไม่ใช่จำกัด
ตัวอย่างที่ 2: ตรวจสอบ 0 และ NaN
#include <cmath>
#include <iostream>
using namespace std;
int main() {
float c = 0.0f, d = -1.0f;
// ตรวจสอบค่าปกติ
isfinite(c) ? cout << "\nเป็นตัวเลขจำกัด" : cout << "\nไม่ใช่ตัวเลขจำกัด";
// sqrt(-1) = NaN
cout << "\nisfinite(sqrt(-1.0)) = " << isfinite(sqrt(d)) << endl;
return 0;
}
ผลลัพธ์ (Output)
เป็นตัวเลขจำกัด isfinite(sqrt(-1.0)) = 0
หมายเหตุ: รากที่สองของ -1.0 จะให้ NaN ซึ่งไม่ใช่ค่าจำกัด
ความสัมพันธ์ระหว่างฟังก์ชันตรวจสอบ floating-point:
| ค่า | isfinite | isinf | isnan | isnormal |
|---|---|---|---|---|
| ปกติ (เช่น 1.0) | 1 | 0 | 0 | 1 |
| Subnormal (denormal) | 1 | 0 | 0 | 0 |
| ศูนย์ (0.0) | 1 | 0 | 0 | 0 |
| +Infinity | 0 | 1 | 0 | 0 |
| -Infinity | 0 | 1 | 0 | 0 |
| NaN | 0 | 0 | 1 | 0 |