【发布时间】:2020-03-31 02:50:30
【问题描述】:
下面的代码看起来很简单。我不明白为什么它不起作用。
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++精灵可以来救我吗?
【问题讨论】:
-
bound_min <= my_variable产生布尔值(在您的情况下为false),false <= bound_max产生? -
你编译了所有警告和调试信息,例如
g++ -Wall -Wextra -g和 GCC ?你读过How to debug small programs 吗?? -
@t.niese 那么评估这种不等式并确保
my_variable在范围内的“正确”方法是什么? -
一旦应用操作顺序,
if (bound_min <= my_variable <= bound_max)->if ((bound_min <= my_variable) <= bound_max)并解析为if ((314.53 <= -417.68) <= 413.09)和if ((false) <= 413.09)。 False 是 0,所以if (0 <= 413.09)是真的。 -
有很多重复:Language support for chained comparison operators (x < y < z)、Why can't I just use 51 <= j <= 55? / data types、100 <= x <= 150 as argument in if (), acting funny、Is (val1 > val2 > val3) a valid comparison in C?、Why do most mainstream languages not support “x < y < z” syntax for 3-way Boolean comparisons?...
标签: c++ operators inequality relational-operators