2017-06-05 67 views
1
int is_infinity/is_zero/is_denormal(float f){ 
    //do something, return 0 or 1 
} 

这是我做过什么检查,如果浮子是负的,我想要做的其他功能类似的东西,但我不知道如何检查浮动是否为无穷大/零/反常规?

int is_negative(float val){ 
    union sp_object copy; 
    copy.frep = val; 
    if((copy.irep & 0x80000000) != 0) 
     return 1; 
    else 
     return 0; 
} 
+3

['std :: isinf'](http://en.cppreference.com/w/cpp/numeric/math/isinf)等可能['std :: fpclassify'](http:// en。 cppreference.com/w/cpp/numeric/math/FP_categories),如果你是各种各样的值。 –

+1

@FrançoisAndrieux - 没关系。 'fpclassify'是C标准库的一部分。 – StoryTeller

+0

@StoryTeller'std :: fpclassify'虽然不是 –

回答

0

ISO C99是如何提供INFINITYNAN可以与之比较的宏。建议使用功能isfinite(),isnormal()isnan()。请注意,EOF指出,与NAN宏比较不会确定值是否实际为NAN

对于C99:

https://www.gnu.org/software/libc/manual/html_node/Floating-Point-Classes.html#Floating-Point-Classes

https://www.gnu.org/software/libc/manual/html_node/Infinity-and-NaN.html

对于早期的代码,你的运气了:

http://c-faq.com/fp/nan.html

+1

由于NAN与所有浮点数和NAN都不相等,因此您无法通过将其与NAN进行比较来找出浮点数是否为NAN。 – EOF

2

我想要做的类似的东西其他功能

避免位字段@David,因为它取决于具体实现。 <math.h>包含用于对float进行分类的宏。这些宏也适用于doublelong double

#include <math.h> 

// Adjust returns values as desired. 
int is_infinity_is_zero_is_denormal(float f) { 
    if (isinf(f)) return 'i'; 
    if (f == 0.0f) return 'z'; 
    if (isnan(f)) return 'n'; 
    if (isnormal(f)) return 0; // neither zero, subnormal, infinite, nor NaN 

    // All that is left is de-normal/sub-normal. 
    return 'd'; 
} 

或者,也许只是

bool is_infinity_is_zero_is_denormal(float f) { 
    return !(isnormal(f) || isnan(f)); 
} 

另见int fpclassify(real-floating x);的数量在一个步骤分类。

将其参数值分类为NaN,无限,正常,低于正常值的零或其他实现定义的类别。 C11§7.12.3.12

bool is_infinity_is_zero_is_denormal(float f) { 
    return fpclassify(f) & (FP_INFINITE | FP_ZERO | FP_SUBNORMAL); 
} 

让编译器处理的优化。