2013-05-09 81 views
2

如何檢查浮點變量是否包含實數或不在C++中?如何檢查float變量是否包含實數或不在C++中?

例如:-1#IND000我的價值

如何判斷它是否是實數或類似上面的數字。

+0

類型的變量??? – 999k 2013-05-09 06:30:51

+0

它浮點變量 – Pixel 2013-05-09 06:32:26

+0

可能的重複:[http://stackoverflow.com/questions/570669/checking-if-a-double-or-float-is-nan-in-c](檢查雙精度或浮點數是nan在C++中) – 2013-05-09 06:41:15

回答

2

在標頭<cmath>中有std::isnan等功能。

+0

當前沒有isnan()函數可用C++標準庫現在 – Pixel 2013-05-09 06:43:03

+0

@HitMe是的。 – juanchopanza 2013-05-09 06:45:45

+0

@HitMe * current * C++標準庫是C++ 11。如果您的編譯器尚不支持C++ 11,則從C99開始,在''中有'isnan'。如果您的編譯器甚至不支持,請考慮升級它。 – Angew 2013-05-09 06:52:05

2

轉換成布爾(明確Ø通過任何邏輯運算的平均值)將給予不屬於「真正的」,或者說是0所有值「假」,所以

bool is_number(double d) 
{ return d || d==0; } 

應該罰款。

1

以下這些返回true如果它是一個數字,false否則:

bool test1(double d) { return d == d; } 
bool test2(double d) { return d * 0.0 == 0.0; } 

這些對Checking if a double (or float) is nan in C++了很好的討論。

1

一個非常簡單的方法..

float a=3.9; 
long b; 
b=a; 
if ((float)b==a) 
    cout<<"Non-real, i.e. integer"; 
else 
    cout<<"REAL"; 
1

您可以使用Visual Studio的_isnan「(它被包含在float.h中):

float T; 

T=std::numeric_limits<double>::quiet_NaN(); //YOUR CALCS HERE!! 

if (_isnan(T)) { 
    printf("error\n"); 
} 
相關問題