错误:二进制表达式('float' 和 'float')返回的无效操作数 (x & (1 << 31)) == 0
error: invalid operands to binary expression ('float' and 'float') return (x & (1 << 31)) == 0
嗨,我有一个类似的代码:
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.
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- System.InvalidCastException - SQL to C++ - safe_cast<float>
- 没有从阵列<float>到阵列<int>的可行转换
- 数组下标的类型"float*[float]"无效
- 没有合适的构造函数可以从"float"转换为"_D3DCOLORVALUE"
- 为什么我会收到此错误?无法将 {lb, ub} 从<大括号括起来的初始值设定项列表>转换为 float(**)(float*, int)
- 将 **float array 从 C++ Dll 传递给 python
- 错误:二进制'operator*' 'float'和'float[0]'类型的操作数无效
- float* 已在 Gameobject.obj 中定义
- 如何将 qml 的文本转换为 float 和 int
- 为什么将 1 添加到 numeric_limits<float>::min() 返回 1?
- 有没有比static_cast更优雅的从int到float的演员阵容<float>?
- 编译器给出错误:format 指定类型 'float *',但参数的类型'double' [-Wformat]
- OPENCL 警告:不兼容的指针类型将'float __global[16]'传递给类型为 '__global float4 的参数 *
- 错误:无法将"float*"转换为"float"
- 如何在函数中将字符串和分数存储为(Int 或 float)
- 缩小从double到float的转换