首页 > 解决方案 > C2296:“|”:非法,左操作数的类型为“float”

问题描述

我试图以一种干净和快速的方式(通过逻辑)比较三个变量是否为 0,它们都是浮点数,IEEE 754。

float x;
float y;
float z;

if(((x | y | z) == 0.0f)) { ... }

但是,我不断得到:

main.cpp(15): error C2296: '|': illegal, left operand has type 'float'
main.cpp(15): error C2297: '|': illegal, right operand has type 'float'
main.cpp(18): error C2296: '|': illegal, left operand has type 'float'
main.cpp(18): error C2297: '|': illegal, right operand has type 'float'

我读过一些关于,

std::numeric_limits<T>::is_iec559
std::numeric_limits<float>::epsilon()
std::fabs()

和厄普西隆10^−7

标签: c++c++11c++17

解决方案


位运算符只为整数类型定义。Afloat不是整数类型。

不要像这样进行微优化。写清楚你的意图,把优化策略留给编译器。


推荐阅读