當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C++ isnan()用法及代碼示例


C++ isnan() 函數

isnan() 函數是 cmath 頭文件的庫函數,用於檢查給定值是否為 NaN (Not-A-Number)。它接受一個值 (floatdouble或者long double),如果給定值為 NaN,則返回 1; 0,否則。

isnan() 函數的語法:

在 C99 中,它已被實現為一個宏,

    macro isnan(x)

在 C++11 中,它已經被實現為一個函數,

    bool isnan (float x);
    bool isnan (double x);
    bool isnan (long double x);

參數:

  • x– 表示要檢查為 NaN 的值。

返回值:

這個函數的返回類型是bool,如果x是 NaN; 0,否則。

例:

    Input:
    float x = 0.0f/0.0f;
    
    Function call:
    isnan(x);    
    
    Output:
    1

    Input:
    float x = sqrt(-1.0f);
    
    Function call:
    isnan(x);    
    
    Output:
    1

    Input:
    float x = 10.0f;
    
    Function call:
    isnan(x);    
    
    Output:
    0

C++代碼演示isnan()函數的例子

// C++ code to demonstrate the example of
// isnan() function

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

int main()
{
    cout << "isnan(sqrt(-10.0f)):" << isnan(sqrt(-10.0f)) << endl;
    cout << "isnan(0.0f/0.0f):" << isnan(0.0f / 0.0f) << endl;
    cout << "isnan(0.0f/1.0f):" << isnan(0.0f / 1.0f) << endl;
    cout << "isnan(1.0f/0.0f):" << isnan(1.0f / 0.0f) << endl;

    float x = sqrt(-1.0f);

    // checking using the condition
    if (isnan(x)) {
        cout << x << " is a NaN." << endl;
    }
    else {
        cout << x << " is not a NaN." << endl;
    }

    x = sqrt(2);

    if (isnan(x)) {
        cout << x << " is a NaN." << endl;
    }
    else {
        cout << x << " is not a NaN." << endl;
    }

    return 0;
}

輸出

isnan(sqrt(-10.0f)):1
isnan(0.0f/0.0f):1
isnan(0.0f/1.0f):0
isnan(1.0f/0.0f):0
-nan is a NaN.
1.41421 is not a NaN.

參考:C++ isnan() 函數



相關用法


注:本文由純淨天空篩選整理自 isnan() Function with Example in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。