int is_infinity/is_zero/is_denormal(float f){
//do something, return 0 or 1
}
这就是我检查float
是否为负数所做的事情。我想对其他功能做类似的事情,但我不知道如何做。
int is_negative(float val){
union sp_object copy;
copy.frep = val;
if((copy.irep & 0x80000000) != 0)
return 1;
else
return 0;
}
最佳答案
I want to do something similar for the other functions
避免位字段,@David ,因为这取决于实现细节。 <math.h>
包含对 float
进行分类的宏。这些宏适用于 double
和long 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);
一步对数字进行分类。
classifies its argument value as NaN, infinite, normal, subnormal, zero, or into another implementation-defined category. C11 §7.12.3.1 2
The number classification macros
FP_INFINITE FP_NAN FP_NORMAL FP_SUBNORMAL FP_ZERO
represent the mutually exclusive kinds of floating-point values. They expand to integer constant expressions with distinct values. §7.12 6
bool is_infinity_is_zero_is_denormal(float f) {
// return fpclassify(f) & (FP_INFINITE | FP_ZERO | FP_SUBNORMAL); // not good
switch (fpclassify(f)) {
case FP_INFINITE:
case FP_ZERO:
case FP_SUBNORMAL:
return true;
}
return false;
}
让编译器处理优化。
关于c - 如何检查 float 是否无穷大/零/非正规?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44376382/