【问题标题】:Why does the following inequality evaluate to true in C++? [duplicate]为什么以下不等式在 C++ 中计算为真? [复制]
【发布时间】: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++精灵可以来救我吗?

【问题讨论】:

标签: c++ operators inequality relational-operators


【解决方案1】:

会发生这种情况: 首先

bound_min <= my_variable

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

false <= bound_max

这是真的。

还有reason

表达式 a() + b() + c() 被解析为 (a() + b()) + c() 因为 operator+的从左到右的结合性

【讨论】:

  • 您能否再详细说明一下您的解释?
  • @AlanSTACK 抱歉,我最初的回答是错误的。我编辑了。现在清楚了吗?
【解决方案2】:

if 语句中的条件

if (bound_min <= my_variable <= bound_max)

等价于

if ( ( bound_min <= my_variable ) <= bound_max)

第一个子表达式 ( bound_min &lt;= my_variable ) 的计算结果为布尔值 false。

所以你有

if ( false  <= bound_max)

在这个结果表达式中,布尔值 false 被转换为整数 0,这是由于积分提升。

if ( 0 <= bound_max)

所以条件的最终值为true

来自 C++ 17 标准(8.9 关系运算符)

1 关系运算符组从左到右

[Example: a<b<c means (a<b)<c and not (a<b)&&(b<c) —end example] .

【讨论】:

    猜你喜欢
    • 2015-07-29
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 2021-05-25
    • 2015-05-09
    • 2018-06-06
    相关资源
    最近更新 更多