具有两个关系运算符的单个变量如何在内部工作

Khu*_*ram 0 c++ boolean-expression logical-operators relational-operators

如果需要组合布尔表达式,我们通常使用逻辑运算符.如果不使用逻辑运算符,我想知道表达式.

int x=101;
if(90<=x<=100)
  cout<<'A';  
Run Code Online (Sandbox Code Playgroud)

此代码仍在控制台上打印"A".你能帮我理解一下这个布尔表达式的评估方式和顺序.

Fra*_*eux 7

由于运算符具有相同的优先级,因此表达式从左到右进行求值:

if( (90 <= x) <= 100 )

if( (90 <= 101) <= 100 ) // substitute x's value

if( true <= 100 ) // evaluate the first <= operator

if( 1 <= 100 ) // implicit integer promotion for true to int

if( true ) // evaluate the second <= operator
Run Code Online (Sandbox Code Playgroud)

要实现您想要的比较,您将使用以下条件:

if( 90 <= x && x <= 100)
Run Code Online (Sandbox Code Playgroud)