为什么以下不等式在 C++ 中的计算结果为真?
Why does the following inequality evaluate to true in 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?");
}
有Whosebug的C++高手能来救救我吗?
事情是这样的:
第一
bound_min <= my_variable
那么接下来使用的结果(false):
false <= bound_max
这是真的。
和reason:
expression a() + b() + c() is parsed as (a() + b()) + c() due to
left-to-right associativity of operator+
if语句中的条件
if (bound_min <= my_variable <= bound_max)
相当于
if ( ( bound_min <= my_variable ) <= bound_max)
第一个子表达式 ( bound_min <= my_variable )
的计算结果为布尔值 false。
所以你有
if ( false <= bound_max)
在此结果表达式中,由于整数提升,布尔值 false
被转换为整数 0
。
if ( 0 <= bound_max)
所以条件的最终值为true
.
来自 C++ 17 标准(8.9 关系运算符)
1 The relational operators group left-to-right.
[Example: a<b<c means (a<b)<c and not (a<b)&&(b<c) —end example] .
下面这段代码看起来很琐碎。我不明白为什么它不起作用。
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?");
}
有Whosebug的C++高手能来救救我吗?
事情是这样的: 第一
bound_min <= my_variable
那么接下来使用的结果(false):
false <= bound_max
这是真的。
和reason:
expression a() + b() + c() is parsed as (a() + b()) + c() due to left-to-right associativity of operator+
if语句中的条件
if (bound_min <= my_variable <= bound_max)
相当于
if ( ( bound_min <= my_variable ) <= bound_max)
第一个子表达式 ( bound_min <= my_variable )
的计算结果为布尔值 false。
所以你有
if ( false <= bound_max)
在此结果表达式中,由于整数提升,布尔值 false
被转换为整数 0
。
if ( 0 <= bound_max)
所以条件的最终值为true
.
来自 C++ 17 标准(8.9 关系运算符)
1 The relational operators group left-to-right.
[Example: a<b<c means (a<b)<c and not (a<b)&&(b<c) —end example] .