错误:二进制表达式('float' 和 'float')返回的无效操作数 (x & (1 << 31)) == 0

error: invalid operands to binary expression ('float' and 'float') return (x & (1 << 31)) == 0

本文关键字:lt float 操作数 二进制 错误 表达式 返回 无效      更新时间:2023-10-16

嗨,我有一个类似的代码:

STATIC bool is_pos_float(float x) {
  return (x & (1 << 31)) == 0;
}

但在编译后,它显示了:

error: invalid operands to binary expression ('float' and 'float')
  return (x & (1 << 31)) == 0;

有什么问题?

内置operator&的左操作数必须是integral类型,而不是floating_point。而是这样做。

inline bool is_pos_float(float x) {
  return x > 0.0f;
}

编辑。假设OP的真正想要的是以浮点格式陷入困境,我认为如果机器很小的Endian,这将起作用。

bool high_bit_zero(float x) {
    constexpr unsigned sz = sizeof(float);
    using raw = unsigned char[sz];
    raw *c = reinterpret_cast<raw*>(&x);
    return !((*c)[sz-1] & (1 << 7));
}

您打算做什么?使用float变量的位播放?

如果您打算确保x为正或零,则解决方案使用!(x<0.0f)

float转换为int导致忽略-1+1之间的少量数字。

如果您坚持做一些骇客的事情,请查看IEEE-754标准:

#include <iostream>
using namespace std;
static bool is_posz_float(float x)
{
  static_assert(sizeof(float) == 4, "Unexpected type size!");
  union IEEE754{
    float number;
    unsigned char bytes[sizeof(float)];
  };
  IEEE754 a;
  a.number=x;
  return (a.bytes[sizeof(float)-1] & (1 << 7)) == 0;
}
void test(float x)
{
    if(is_posz_float(x))
        cout<<x<<" is a positive number or zero."<<endl;
    else
        cout<<x<<" is a negative number."<<endl;
}

int main() {
    test(0.1f);
    test(0.0f);
    test(3.14f);
    test(-0.11);
    return 0;
}

结果:

0.1 is a positive number or zero.
0 is a positive number or zero.
3.14 is a positive number or zero.
-0.11 is a negative number.