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;
}
,因为这取决于实现细节。avoid位字段,
@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';
}
另外,请参见一步中对数字进行分类。
将其参数价值分为NAN,无限,正常,次正常,零或另一个实现定义的类别。 C11§7.12.3.12数字分类宏
bool is_infinity_is_zero_is_denormal(float f) {
return !(isnormal(f) || isnan(f));
}
表示互斥的浮点值。它们扩展到具有不同值的整数常数表达式。 §7.126
int fpclassify(real-floating x);
let编译器处理优化。,ISOC99提供了一个可以将其与之比较的宏和宏。建议使用函数
FP_INFINITE FP_NAN FP_NORMAL FP_SUBNORMAL FP_ZERO
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;
}
和INFINITY
。请注意,正如EOF指出的那样,与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-and-nan.html
对于较早的代码,您是不幸的:
http://c-faq.com/fp/nan.html