首页 > 解决方案 > 为什么以下不等式在 C++ 中计算为真?

问题描述

下面这段代码看起来很简单。我不明白为什么它不起作用。

float bound_min   = +314.53f;
float bound_max   = +413.09f;
float my_variable = -417.68f;

if (bound_min <= my_variable <= bound_max)
{
    printf("Why on earth is this returning True?");
}   

请问stackoverflow的C++向导可以来救我吗?

标签: c++operatorsinequalityrelational-operators

解决方案


这就是发生的事情:首先

bound_min <= my_variable

然后结果(假)用于下一个:

false <= bound_max

这是真的。

原因:_

由于 operator+ 的从左到右的关联性,表达式 a() + b() + c() 被解析为 (a() + b()) + c()


推荐阅读