標題中的兩個函數,在qt4.7版本中沒有實現,但是在 Assistant 中索引可以,但是文檔中沒有介紹,
所以在代碼中直接調用的時候,會報錯。
c++ 也是從11標准之后std 才實現 isinf 和 isnan 這樣的功能,
而我使用的開發平台:qt4 vs2008 顯然不能期望通過直接使用現有的庫函數了
在Qt5.6 版本的幫助文檔中,這么描述:
bool qIsInf(float f)
Returns true if the float f is equivalent to infinity.
bool qIsNaN(float f)
Returns true if the float f is not a number (NaN).
尋思着自己實現,參照qt高版本怎么實現的,
qt5.6 源代碼目錄位置: C:\Qt\Qt5.6.0\5.6\Src\qtbase\src\corelib\global
三個源文件:
qnumeric.h //部分代碼段 #ifndef QNUMERIC_H #define QNUMERIC_H #include <QtCore/qglobal.h> QT_BEGIN_NAMESPACE Q_CORE_EXPORT bool qIsInf(double d); Q_CORE_EXPORT bool qIsNaN(double d); Q_CORE_EXPORT bool qIsInf(float f); Q_CORE_EXPORT bool qIsNaN(float f); QT_END_NAMESPACE #endif // QNUMERIC_H
qnumeric.cpp 部分代碼段 #include "qnumeric.h" #include "qnumeric_p.h" //從這里可以判斷,qt_is_inf qt_is_nan的實現在這個頭文件中 #include <string.h> QT_BEGIN_NAMESPACE /*! Returns \c true if the double \a {d} is equivalent to infinity. \relates <QtGlobal> */ Q_CORE_EXPORT bool qIsInf(double d) { return qt_is_inf(d); } /*! Returns \c true if the double \a {d} is not a number (NaN). \relates <QtGlobal> */ Q_CORE_EXPORT bool qIsNaN(double d) { return qt_is_nan(d); }/*! Returns \c true if the float \a {f} is equivalent to infinity. \relates <QtGlobal> */ Q_CORE_EXPORT bool qIsInf(float f) { return qt_is_inf(f); } /*! Returns \c true if the float \a {f} is not a number (NaN). \relates <QtGlobal> */ Q_CORE_EXPORT bool qIsNaN(float f) { return qt_is_nan(f); }
qnumeric_p.h 頭文件中部分代碼段 static inline bool qt_is_inf(float d) { uchar *ch = (uchar *)&d; if (QSysInfo::ByteOrder == QSysInfo::BigEndian) { return (ch[0] & 0x7f) == 0x7f && ch[1] == 0x80; } else { return (ch[3] & 0x7f) == 0x7f && ch[2] == 0x80; } } static inline bool qt_is_nan(float d) { uchar *ch = (uchar *)&d; if (QSysInfo::ByteOrder == QSysInfo::BigEndian) { return (ch[0] & 0x7f) == 0x7f && ch[1] > 0x80; } else { return (ch[3] & 0x7f) == 0x7f && ch[2] > 0x80; } }
這么樣的話,就很容易拷貝過來在 qt4中使用了,
// 數值范圍判斷 參考 qt5.6源代碼 qnumeric.cpp qnumeric_p.h // 源碼目錄: C:\Qt\Qt5.6.0\5.6\Src\qtbase\src\corelib\global static inline bool qIsInf_craig(float f) { return qt_is_inf(f); } static inline bool qt_is_inf(float d) { uchar *ch = (uchar *)&d; if (QSysInfo::ByteOrder == QSysInfo::BigEndian) { return (ch[0] & 0x7f) == 0x7f && ch[1] == 0x80; } else { return (ch[3] & 0x7f) == 0x7f && ch[2] == 0x80; } } static inline bool qIsNaN_craig(float f) { return qt_is_nan(f); } static inline bool qt_is_nan(float d) { uchar *ch = (uchar *)&d; if (QSysInfo::ByteOrder == QSysInfo::BigEndian) { return (ch[0] & 0x7f) == 0x7f && ch[1] > 0x80; } else { return (ch[3] & 0x7f) == 0x7f && ch[2] > 0x80; } }
QSysInfo::ByteOrder == QSysInfo::BigEndian
需要包含 頭文件 #include <QSysInfo>
目前使用還可以,還沒有出現不正確的結果,需要繼續觀察
感謝上帝,